Skip to content
Engineering Bible
SQL and Databases

SQL and Databases on indexes

An index trades write speed for read speed

  • Without an index, the database reads every row to find a match: a sequential scan.
  • An index is a sorted copy of some columns, with a pointer back to each row.
  • Every insert must also update every index. Add the ones your queries need, no more.

A B-tree finds a row in a few steps

  • The default index is a B-tree: a sorted tree whose leaves all sit at the same depth.
  • A lookup walks from the root down to one leaf, one node per level.
  • With millions of rows, the tree is only four or five levels deep.
  • Leaves are linked in sorted order, so ranges like created_at > $1 are fast too.
  1. Root nodewhich branch holds 57?
  2. Branch nodewhich leaf holds 57?
  3. Leaf nodeentry 57 and its row location
  4. Tablefetch the full row
Looking up id = 57: one node read per level, then one read of the table.

Column order decides what a composite index can do

  • An index on (user_id, created_at) is sorted by user_id, then by created_at.
  • It is like a phone book: sorted by surname, then first name.
  • It works best when the query pins user_id. It gives little help for created_at alone.
  • Put columns you test with = first, then the one you range over or sort by.

A covering index answers without touching the table

  • If an index holds every column a query uses, PostgreSQL can skip the table.
  • That is an index-only scan. INCLUDE adds extra columns to an index just for this.
  • Included columns make the index bigger. Add them only for queries that run a lot.
CREATE INDEX orders_user_created_idx
  ON orders (user_id, created_at) INCLUDE (total);

SELECT created_at, total
FROM orders
WHERE user_id = 42
  AND created_at >= now() - interval '7 days';
The index finds user 42, reads one date range, and already holds total.

A function on a column hides it from its index

  • WHERE lower(email) = $1 cannot use a plain index on email.
  • Index the expression itself: CREATE INDEX ON users (lower(email)).
  • A partial index covers only some rows: add WHERE total > 1000 to index big orders only.

Build indexes on live tables with CONCURRENTLY

  • A plain CREATE INDEX blocks every write to the table until it finishes.
  • CREATE INDEX CONCURRENTLY lets writes carry on. It scans the table twice and takes longer.
  • If it fails, it leaves an invalid index behind. Drop that index and run it again.
SQL and Databases in seven pages3 / 7