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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- Which tables does the SQL touch?
- The references are `sessions`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.