// dialect comparison

Custom sort order: CASE, FIELD and DECODE

Alphabetical order is wrong for statuses; map them to a rank instead.

Filed under Querying

The verdict

CASE is the portable form and states the mapping in readable SQL; FIELD and DECODE are terser engine dialects. If the ranking changes at runtime or has more than a handful of values, stop encoding it in ORDER BY and give the table a sort_order column.

Where they differ

Sort on an expression that maps each value to its position: a CASE expression works everywhere, MySQL's FIELD() lists the values directly, and Oracle's DECODE does the same in one line.

How each engine writes it

SQL Server

SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;

Unknown values fall into ELSE; put the mapping in a lookup table with a sort_order column if it grows.

PostgreSQL

SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;

An enum type sorts by its declaration order, an alternative worth knowing for fixed sets.

MySQL

SELECT * FROM tickets ORDER BY FIELD(severity, 'low', 'high', 'critical') DESC;

FIELD() returns the 1-based position and 0 for values not in the list. Listing the values in reverse and sorting DESC puts critical first and unknown values (0) last, like the ELSE 3 in the other rows.

SQLite

SELECT * FROM tickets ORDER BY CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 2 ELSE 3 END;

No FIELD(); CASE is the only option.

Oracle

SELECT * FROM tickets ORDER BY DECODE(severity, 'critical', 0, 'high', 1, 'low', 2, 3);

The last DECODE argument is the default for unmatched values; CASE reads the same.

Questions that come up

How do I sort in a custom order but keep a secondary key?

List several keys: ORDER BY CASE … END, created_at. The CASE ranks first, and rows inside each rank are ordered by created_at, like any other multi-key sort.

Why do unmatched values sort first with FIELD?

FIELD returns 0 when the value isn't in the list, and 0 sorts before 1, 2, 3 in ascending order. Either list the values in reverse and sort DESC, as the MySQL row does, or sort on FIELD(…) = 0 first: ORDER BY FIELD(severity, 'critical', 'high', 'low') = 0, FIELD(severity, 'critical', 'high', 'low'). A CASE with an explicit ELSE also works.

Should I store the sort rank in the table instead?

Usually yes once the list is stable: a sort_order smallint column (or a PostgreSQL enum) sorts with a plain ORDER BY, uses a normal index, and lets the application reorder values without editing every query.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.