Concept · Basic queries

NULLS FIRST and NULLS LAST in ORDER BY

NULLS FIRST and NULLS LAST decide where NULLs appear when sorting. ASC and DESC decide the order of the known values.

Before continuing: This entry is part of the NULL guide. If you are new to the topic, start with IS NULL / IS NOT NULL.

Example

Customers sorted by email
SELECT id, name, email
FROM customers
ORDER BY email ASC NULLS LAST, id;

email ASC sorts the known email addresses alphabetically and NULLS LAST moves the three missing values to the end. id breaks ties between rows that share the same email or are both NULL.

How it is used

ASC or DESC sets how the known values are sorted. Where NULL end up by default can vary between engines. If your requirement says “known emails first” or “missing dates last”, state it explicitly.

Do not trust a casual observation. A small data set that always shows NULLs last does not make that a portable rule across databases.

What changes from case to case

CASE alternative when the engine lacks the syntax

A sort expression can separate the NULL rows first and then sort by the value itself:

CASE pattern
SELECT id, name, email
FROM customers
ORDER BY
  CASE WHEN email IS NULL THEN 1 ELSE 0 END,
  email ASC,
  id;

The first criterion returns 0 for known emails and 1 for NULL. Because the sort is ascending, known values come first. It is longer, but it states the intent clearly even where NULLS LAST is not available.

With several columns, each sort key has its own rule

In ORDER BY date NULLS LAST, id DESC, the NULL rule applies to date. The second key only breaks ties between rows that the first key left in the same position.

Key differences between engines

PostgreSQL supports NULLS FIRST and NULLS LAST and documents that NULLs sort as larger than any non-null value by default: with ASC they come last and with DESC they come first. SQLite also supports both options; by default it treats NULL as smaller than any other value.

MySQL documents a different default: NULL comes first in ascending order and last in descending order. If you need the same result on several engines, an expression with CASE avoids depending on those differences.