NULLS LAST Ordering Needs Index Match

PostgreSQL treats NULL as largest, so DESC defaults to NULLS FIRST; ORDER BY DESC NULLS LAST matches only an index created with the same explicit NULLS LAST.

SqlData Fetching

Code

snippet
-- PG treats NULL as largest by default: ASC defaults to NULLS LAST, DESC to NULLS FIRST
-- A query wanting DESC NULLS LAST does not match a plain (started_at DESC) index's sort specification
CREATE INDEX idx_sessions_started_desc
    ON sessions (started_at DESC);

-- This query falls back to a Sort node (or a seq scan on small tables):
-- SELECT id, started_at FROM sessions
-- ORDER BY started_at DESC NULLS LAST LIMIT 10;

-- Declare NULLS LAST at index creation so the column sort spec matches the ORDER BY exactly
CREATE INDEX idx_sessions_started_desc_nulls_last
    ON sessions (started_at DESC NULLS LAST);

SELECT id, started_at
FROM sessions
ORDER BY started_at DESC NULLS LAST
LIMIT 10;

How it works

Several statements share this file — SELECT / CREATE, with sessions among the objects involved.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Using it

Point it at the sessions table — the LIMIT keeps the probe cheap while you tune the predicates.

Key statements

CREATE INDEX idx_sessions_started_desc_nulls_last
ON sessions (started_at DESC NULLS LAST);
SELECT id, started_at
FROM sessions
ORDER BY started_at DESC NULLS LAST
LIMIT 10;
CREATE INDEX idx_sessions_started_desc
ON sessions (started_at DESC);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `sessions`.