Menu
Coddy logo textTech

CASE in ORDER BY

Part of the Beyond the Basics section of Coddy's SQL journey — lesson 2 of 27.

CASE isn't only for SELECT. You can put it inside ORDER BY to sort rows by a custom rule that the columns alone can't express.

SELECT name, status
FROM tickets
ORDER BY
    CASE status
        WHEN 'urgent' THEN 1
        WHEN 'high'   THEN 2
        WHEN 'normal' THEN 3
        ELSE 4
    END

Notice the shorter form: CASE column WHEN value THEN .... It's equivalent to WHEN column = value. Use whichever reads more cleanly.

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>tasks</strong>: <strong>id</strong>, <strong>title</strong>, <strong>priority</strong>

Return title and priority, ordered so that 'critical' comes first, then 'high', then 'low', and anything else last. Within the same priority, sort by title alphabetically.

Cheat sheet

Use CASE inside ORDER BY to sort by a custom rule:

SELECT name, status
FROM tickets
ORDER BY
    CASE status
        WHEN 'urgent' THEN 1
        WHEN 'high'   THEN 2
        WHEN 'normal' THEN 3
        ELSE 4
    END

The short form CASE column WHEN value THEN ... is equivalent to CASE WHEN column = value THEN ....

Try it yourself

SELECT title, priority
FROM tasks
ORDER BY
    -- ...
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Beyond the Basics