// window reference

SQL NULLS FIRST and NULLS LAST

NULLS FIRST or NULLS LAST pins NULL ordering inside windows, where each engine's implicit rule otherwise decides, and they disagree.

Catégorie
Fenêtre
Returns
ordered partition
In this category
45 of 79

Syntaxe

ORDER BY x NULLS LAST | ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x (portable emulation)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in no NULLS FIRST/LAST clause; emulate with ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x
PostgreSQL Oui Supported under this name.
MySQL Not built in no NULLS FIRST/LAST clause; NULLs sort first ascending, last descending; emulate with the CASE trick
SQLite Oui SQLite 3.30+; default treats NULL as smallest
Oracle Oui default treats NULL as largest (last ascending, first descending), same as PostgreSQL

Exemples

PostgreSQL

SELECT name, priority,
       ROW_NUMBER() OVER (ORDER BY priority NULLS LAST) AS rn
FROM tasks;

SQL Server

SELECT name, priority,
       ROW_NUMBER() OVER (ORDER BY CASE WHEN priority IS NULL THEN 1 ELSE 0 END, priority) AS rn
FROM tasks;

Bon à savoir

  • Defaults split into two camps: PostgreSQL and Oracle treat NULL as larger than any value (last ascending, first descending); SQL Server, MySQL and SQLite treat it as smaller (first ascending, last descending).
  • In windows the placement changes results, not just display: ROW_NUMBER() OVER (ORDER BY score DESC) gives rn = 1 to a NULL score on PostgreSQL and Oracle, and to the highest real score on the other three.
  • ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x puts NULLs last on every engine; swap 1 and 0 for NULLs first. The shorter ORDER BY x IS NULL, x works on PostgreSQL, MySQL, SQLite and Oracle 23ai but not SQL Server.

Questions about NULLS FIRST / NULLS LAST

Where do NULLs sort by default?

PostgreSQL and Oracle sort NULLs last ascending and first descending. SQL Server, MySQL and SQLite do the opposite: first ascending, last descending. Write NULLS FIRST/LAST where supported, or the CASE sort key elsewhere.

Do NULLs affect LAG and LEAD?

LAG and LEAD return the neighbouring row's value even when it is NULL. To skip NULLs you need IGNORE NULLS (Oracle, SQL Server 2022+) or the COUNT/MAX emulation.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.