Video in progress
What should the index look like for the query `ORDER BY created_at DESC LIMIT 20`, and how does `NULLS FIRST/LAST` affect it?
A B-tree can be read in both directions, so a plain (created_at) index works for DESC too. But if a multi-column order has mixed directions, or the NULLS order doesn't match the index's, the planner adds a sort and reads all the rows.
📖 Answer
With a single column, a plain index is enough:
CREATE INDEX ON posts (created_at);
-- ORDER BY created_at DESC LIMIT 20 -> Index Scan Backward, only 20 rows
But in DESC order PostgreSQL puts NULLs first by default (NULLS FIRST). If the query says ORDER BY created_at DESC NULLS LAST, the plain index order doesn't match and a Sort appears. In that case the index is created like this:
CREATE INDEX ON posts (created_at DESC NULLS LAST);
The multi-column case:
-- the query
SELECT * FROM posts
WHERE author_id = 7
ORDER BY pinned DESC, created_at DESC
LIMIT 20;
-- the matching index
CREATE INDEX ON posts (author_id, pinned DESC, created_at DESC);
With ORDER BY pinned DESC, created_at ASC, you can read a (pinned, created_at) index neither forward nor backward, because the directions are mixed. The index has to be created with exactly that mixed order.
It's easy to check: in EXPLAIN, Limit -> Index Scan is good. If it's Limit -> Sort -> Seq Scan, the database reads all the rows, sorts them, and returns 20.
Sign up to mark studied questions and save your progress.