SQL Tutorial – Sort data based on conditions in ORDER BY clause.

Suppose you have a table and you don’t just want to sort the table in ascending or descending order but you want to sort them based on some conditions or logic.

Here, we have a film table and we want to sort the data by length if it’s a Documentary movie otherwise we want to sort it by price.

Solution –

To solve this problem we can use the CASE expression in the ORDER BY clause to sort the data based on our conditions.

SELECT
    title,
    category,
    price,
    length
FROM
    film_list
ORDER BY
    CASE
        WHEN category = 'Documentary' then length
        ELSE price
    END DESC

Rating: 1 out of 5.

Leave a Reply