How an index makes a Postgres query fast
You add an index and a slow query becomes instant. Here is what Postgres does differently, drawn one page read at a time.
01 The query
A sign-in page looks a user up by email. The table is stored on disk in fixed-size pages, and each page holds a handful of rows. Reading a page is the expensive part, so we will count those.
02 Without an index: read everything
With no index, Postgres does a sequential scan. It reads every page, checks every row, and keeps going even after it finds Ana, because nothing tells it there isn’t a second match further on.
- reading now
- read, no match
- Ana’s row
- not read yet
Postgres starts at page 1. Nothing is read yet.
03 With an index: walk the tree
A normal Postgres index is a B-tree: a separate, sorted structure of emails. Each email in the bottom layer points to the exact page and row where that user lives. Finding Ana means walking down from the top, one page per level.
- pointer followed
- compared
- path taken
- Ana
- not read yet
Postgres has the query and the index. Nothing is read yet.
04 Ask Postgres what it did
Put EXPLAIN in front of the query to see the plan. The first line tells you which walk it chose.
Seq Scan on usersFilter: (email = 'ana@x.com')
Index Scan using users_email_idx on usersIndex Cond: (email = 'ana@x.com')
05 Add the index
On a live table, a plain CREATE INDEX blocks writes until it finishes. Use CREATE INDEX CONCURRENTLY: it is slower to build, but inserts and updates keep working.
06 When the index won’t help
email LIKE '%@x.com'A wildcard at the startThe tree is sorted from the first character. With no known start, there is nowhere to begin the walk.lower(email) = 'ana@x.com'A function on the columnThe index holds email, not lower(email). Index the expression itself: CREATE INDEX ON users (lower(email)).status = 'active'Most rows matchIf the query returns a big share of the table, jumping around costs more than reading straight through. The planner picks the scan.INSERT / UPDATEWrites pay for itEvery insert, and every update that changes email, also updates the tree. Index what you search, not every column.