SQL NULL sort order
Controls whether NULL rows sort at the top or bottom of an ordered result.
- 类别
- 条件
- Returns
ordering modifier- In this category
- 33 of 43
语法
ORDER BY x NULLS FIRST | ORDER BY x NULLS LAST | ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | no NULLS FIRST/LAST; emulate with CASE |
| PostgreSQL | 是 | NULLs sort last in ASC by default (NULL treated as largest) |
| MySQL | Not built in | no syntax; NULLs sort first in ASC and last in DESC |
| SQLite | 是 | 3.30+; NULLs sort first in ASC by default |
| Oracle | 是 | NULLs sort last in ASC by default; NULLS FIRST/LAST supported |
示例
PostgreSQL
SELECT * FROM races ORDER BY finish_time NULLS LAST;
SQL Server
SELECT * FROM races ORDER BY CASE WHEN finish_time IS NULL THEN 1 ELSE 0 END, finish_time;
值得了解
- The defaults disagree: SQL Server, MySQL and SQLite put NULLs first in ASC; PostgreSQL and Oracle put them last. The same query orders differently across engines.
- DESC reverses the NULL placement too, unless you pin it with NULLS FIRST or NULLS LAST.
- The CASE workaround sorts NULLs into a fixed group first (or last, with 1/0 swapped), then orders the values within each group.
Questions about NULLS FIRST
Where do NULLs sort by default?
Engine-dependent: first in SQL Server, MySQL and SQLite; last in PostgreSQL and Oracle (ascending). Pin it with NULLS FIRST/LAST.
Does SQL Server support NULLS LAST?
No; emulate with ORDER BY CASE WHEN x IS NULL THEN 1 ELSE 0 END, x.
Do NULLS FIRST and DESC combine?
Yes: NULLS FIRST/LAST always wins over the direction's default placement.
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.