// dialect comparison

Sorting with COALESCE in ORDER BY

Fold NULL into the value order, or park it deliberately.

Filed under Querying

The verdict

COALESCE in ORDER BY runs on every engine and does one thing: it sorts each NULL as a value you choose. When you only care whether NULLs come first or last, NULLS FIRST/LAST (PostgreSQL, Oracle, SQLite 3.30+) states that more directly.

Where they differ

ORDER BY COALESCE(nullable_col, fallback) sorts on the substituted value instead of using the engine's default NULL placement. It is the portable way to say "treat NULL as X"; the NULLS FIRST/LAST keywords only move NULLs to one end.

How each engine writes it

SQL Server

SELECT * FROM plans ORDER BY COALESCE(promo_price, price);

Without COALESCE, plans with no promo price would sort first, because SQL Server treats NULL as the lowest value.

PostgreSQL

SELECT * FROM plans ORDER BY COALESCE(promo_price, price);

If you only want NULLs at one end, ORDER BY promo_price NULLS LAST says that directly.

MySQL

SELECT * FROM plans ORDER BY COALESCE(promo_price, price);

MySQL sorts NULLs first ascending; IFNULL(promo_price, price) is the two-argument equivalent.

SQLite

SELECT * FROM plans ORDER BY COALESCE(promo_price, price);

SQLite sorts NULLs first ascending; IFNULL works the same here.

Oracle

SELECT * FROM plans ORDER BY NVL(promo_price, price);

NVL is the Oracle spelling; COALESCE gives the same order. Without it, NULLs sort last ascending.

Questions that come up

When should I use COALESCE instead of NULLS LAST?

When a NULL should sort among the values. COALESCE(promo_price, price) places a plan without a promo at its normal price, somewhere in the middle; NULLS FIRST/LAST can only push it to an end.

Can I mix COALESCE with other sort keys?

Yes: ORDER BY COALESCE(promo_price, price), name. Each key is independent, so COALESCE keys combine with plain columns, CASE keys and NULLS FIRST/LAST on other keys.

Does sorting on an expression lose the index?

Usually. A B-tree on promo_price does not match COALESCE(promo_price, price). PostgreSQL, Oracle, SQLite and MySQL 8.0.13+ can index the exact expression; SQL Server can index a computed column. For reports over a few thousand rows the sort is cheap anyway.

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.