// conditional reference

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.

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.