Example 1
Show in-progress tasks first, then open, then closed
The CASE expression maps each status string to a numeric priority: in_progress → 1, open → 2, closed → 3. The ORDER BY sorts by that number, then by id as a tiebreaker so that the two open tasks appear in a stable order. The CASE result does not appear in the output columns.
CREATE TABLE tasks (id INT, name VARCHAR(50), status VARCHAR(20));
INSERT INTO
tasks
VALUES
(1, 'Fix bug', 'open'),
(2, 'Write docs', 'closed'),
(3, 'Deploy', 'in_progress'),
(4, 'Review', 'open');SELECT
id,
name,
status
FROM
tasks
ORDER BY
CASE status
WHEN 'in_progress' THEN 1
WHEN 'open' THEN 2
WHEN 'closed' THEN 3
ELSE 4
END,
id;| id | name | status |
|---|---|---|
| 3 | Deploy | in_progress |
| 1 | Fix bug | open |
| 4 | Review | open |
| 2 | Write docs | closed |
Identical syntax and result across all engines.