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.
- 类别
- 窗口
- Returns
ordered partition- In this category
- 45 of 79
语法
ORDER BY x NULLS LAST | ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x (portable emulation)
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| 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 | 是 | 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 | 是 | SQLite 3.30+; default treats NULL as smallest |
| Oracle | 是 | default treats NULL as largest (last ascending, first descending), same as PostgreSQL |
示例
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;
值得了解
- 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.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.
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.