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.
Fold NULL into the value order, or park it deliberately.
Filed under Querying
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.
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.
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.
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.
SELECT * FROM plans ORDER BY COALESCE(promo_price, price);
MySQL sorts NULLs first ascending; IFNULL(promo_price, price) is the two-argument equivalent.
SELECT * FROM plans ORDER BY COALESCE(promo_price, price);
SQLite sorts NULLs first ascending; IFNULL works the same here.
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.
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.
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.
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.
Three engines support the keywords; two need a sort-key trick.
COALESCE everywhere; ISNULL, IFNULL and NVL are the same idea with local names.
Alphabetical order is wrong for statuses; map them to a rank instead.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.