Rank by several conditions
The CASE maps business severity to numbers; the window sorts by the result.
The task
You want orders ranked into a handling queue: returned orders first, then pending, then shipped, oldest first within each class.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT id, status, order_date,
ROW_NUMBER() OVER (
ORDER BY CASE status
WHEN 'returned' THEN 1
WHEN 'pending' THEN 2
WHEN 'shipped' THEN 3
ELSE 4
END,
order_date
) AS handling_priority
FROM orders
WHERE status <> 'cancelled'
ORDER BY handling_priority;
工作原理
The CASE turns each status into a priority number, and the window ORDER BY sorts first by that number and then by date inside each class. ROW_NUMBER over the combined key hands out queue positions in exactly that order. Ranking by an expression like this is legal anywhere an ORDER BY is, including PARTITION BY for per-region queues.
Variations
Ranked inside each region
SELECT c.region, o.id, o.status,
ROW_NUMBER() OVER (
PARTITION BY c.region
ORDER BY CASE o.status
WHEN 'returned' THEN 1
WHEN 'pending' THEN 2
ELSE 3
END,
o.order_date
) AS queue_position
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY c.region, queue_position;
Questions that come up
How do NULLs sort in the priority ladder?
The CASE's ELSE catches them, so an unknown status lands last instead of wherever the engine puts NULLs. In the main query a NULL status never gets that far: status <> 'cancelled' is unknown for NULL, so WHERE drops the row; write WHERE status IS NULL OR status <> 'cancelled' to keep it. PostgreSQL, Oracle and SQLite 3.30+ also accept NULLS LAST in ORDER BY; SQL Server and MySQL need the CASE.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.