// dialect comparison

Sorting NULLs first or last

Three engines support the keywords; two need a sort-key trick.

Filed under Querying

The verdict

NULLS FIRST/LAST says exactly what you mean; use it on PostgreSQL, Oracle and SQLite 3.30+. The IS NULL or CASE sort key works on all five and is worth knowing, because the defaults disagree: SQL Server, MySQL and SQLite treat NULL as the smallest value, PostgreSQL and Oracle as the largest, and a ported query silently reorders.

Where they differ

The standard NULLS FIRST / NULLS LAST modifiers work in PostgreSQL, Oracle and SQLite 3.30+. SQL Server and MySQL don't have them, so you sort on a computed key (CASE or col IS NULL) ahead of the real column.

How each engine writes it

SQL Server

SELECT * FROM employees ORDER BY CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END, deleted_at;

No NULLS FIRST/LAST. SQL Server treats NULL as the lowest value, so it sorts first ascending; the CASE key pushes it last.

PostgreSQL

SELECT * FROM employees ORDER BY deleted_at NULLS LAST;

PostgreSQL treats NULL as the highest value: NULLS LAST is already the ascending default and NULLS FIRST the descending one.

MySQL

SELECT * FROM employees ORDER BY deleted_at IS NULL, deleted_at;

No NULLS keyword. NULLs sort first ascending; deleted_at IS NULL is 0 or 1, so sorting on it first pushes NULLs last.

SQLite

SELECT * FROM employees ORDER BY deleted_at NULLS LAST;

NULLS FIRST/LAST since 3.30; before that, sort on deleted_at IS NULL first. SQLite sorts NULLs first ascending by default.

Oracle

SELECT * FROM employees ORDER BY deleted_at NULLS LAST;

Same defaults as PostgreSQL: NULLs last ascending, first descending.

Questions that come up

What are the defaults in each engine?

Ascending: SQL Server, MySQL and SQLite put NULLs first; PostgreSQL and Oracle put them last. Descending reverses each engine's order, so DESC puts NULLs last in SQL Server, MySQL and SQLite and first in PostgreSQL and Oracle. The standard leaves this to the implementation.

Why does ORDER BY … DESC LIMIT 10 show NULLs first on PostgreSQL?

Because PostgreSQL and Oracle treat NULL as larger than any value, a descending sort starts with them. On SQL Server, MySQL and SQLite the same query shows them last. Add NULLS LAST, or a CASE key, so the top ten mean the same thing everywhere.

Does the emulation hurt performance?

The extra sort key means an index on deleted_at can no longer deliver rows in order, so the engine sorts. If that matters, index the expression (PostgreSQL, Oracle, MySQL 8.0.13+) or a computed column (SQL Server). PostgreSQL can also build the index itself with NULLS FIRST or LAST to match the query.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.