Ravindra BagaleCourses & study guides Track your progress

8. CASE WHEN: If-Then Logic in SQL

8.4 CASE Inside ORDER BY (Custom Sort Order)

Why. Sometimes High priority must sort before Low even if text order disagrees.

What. CASE in ORDER BY assigns a sort key number to each label.

How. ORDER BY CASE priority WHEN 'High' THEN 1 WHEN 'Medium' THEN 2 ELSE 3 END

Steps

  1. Map High→1, Medium→2, Low→3, else 4.
  2. ORDER BY that CASE.
  3. Scan the result order.

Examples

Example 1 · dataset: interview_mini

SELECT ticket_id, priority, status
FROM tickets
ORDER BY CASE priority
  WHEN 'High' THEN 1
  WHEN 'Medium' THEN 2
  WHEN 'Low' THEN 3
  ELSE 4 END,
  ticket_id;

Output

ticket_idprioritystatus
1HighOpen
4HighOpen
7HighClosed
3MediumOpen
8MediumOpen
2LowClosed
5LowClosed
6Open

Meaning. High tickets first, NULL priority last.

Ravindra Bagale's Tip

Custom sort with CASE is an interview favourite.