How an index finds rows
Without an index, finding email = 'ana@example.com' means reading every row of customers and checking each one. That’s a sequential scan: fine for 1,000 rows, slow for 50 million.
A database indexDatabase indexA sorted structure on one or more columns that lets the database find rows without reading the whole table.Open in glossary → works like the index at the back of a book: a sorted list of values, each pointing to where the row is. Because it’s sorted, the database can jump to the right place instead of reading everything. Most indexes are a B-treeB-treeThe sorted, shallow tree most database indexes use, so a lookup reads a few pages even in a huge table.Open in glossary →, a sorted tree only 3 or 4 levels deep even for millions of rows, so a lookup reads a handful of pages.
CREATE INDEX orders_customer_id ON orders (customer_id);An index on a column helps:
WHERE customer_id = 42(equality)WHERE created_at >= '2026-11-01'(ranges,BETWEEN,<,>)ORDER BY created_at(the index is already sorted)JOIN … ON o.customer_id = c.id(finding the matching rows)
It isn’t free. Every INSERT, UPDATE and DELETE must update every index on the table too, and indexes take disk space. So you add them for the queries the app actually runs, not for every column.
Primary keys and UNIQUE columns get an index automatically. Foreign keys don’t, in PostgreSQL.
One rule catches everyone: the index is on the column, not on what you compute from it. WHERE lower(email) = 'ana@example.com' or WHERE created_at::date = '2026-11-14' asks about a calculated value that isn’t in the index, so the database falls back to reading the whole table.
B-tree internals: pages of sorted keys; inner pages fan out to hundreds of children, so depth stays 3 to 4 for hundreds of millions of rows. Leaf pages are linked, which makes range scans and ordered reads sequential. A leaf entry holds the key and the row’s location (TID); PostgreSQL then fetches the row from the heap (an Index Scan), unless every needed column is in the index and the page is marked all-visible (an Index Only Scan). Many matching rows on scattered pages → a Bitmap Heap Scan, which sorts locations first to read each page once.
Index types (PostgreSQL):
| Type | For |
|---|---|
| B-tree | equality, ranges, sorting, LIKE 'abc%'; the default |
| Hash | equality only; rarely better than B-tree |
| GIN | “contains”: jsonb @>, arrays, full-text search, trigram LIKE '%x%' |
| GiST / SP-GiST | ranges, geometry, nearest-neighbor, exclusion constraints |
| BRIN | huge append-only tables whose order follows a column (time series); tiny |
Costs: write amplification (every index updated per insert; an update to any indexed column creates new index entries; PostgreSQL’s HOT updates avoid that only when no indexed column changes and the page has room), bloat, more WAL and replication traffic, planner time. Find unused indexes with pg_stat_user_indexes.idx_scan = 0 (check replicas too before dropping).
Sargability: a predicate can use an index only when the indexed expression appears bare on one side. lower(email) needs an expression index ON customers (lower(email)); created_at::date = d becomes created_at >= d AND created_at < d + 1; implicit casts (comparing a text column to a number, varchar to nvarchar in SQL Server) silently disable indexes.
Predict the output
customers has 5 million rows and a UNIQUE index on email. Which plan does this query get?
EXPLAIN SELECT id FROM customers WHERE lower(email) = 'ana@example.com';The index stores email as it is, sorted. The query asks about lower(email), a value the index doesn't contain, so the planner can't use it and reads the whole table. Fix it with an expression index, CREATE INDEX ON customers (lower(email)), or store emails already lowercased (or use the citext type). Then the plan becomes an Index Scan.
-- joins and "orders of this customer"
CREATE INDEX orders_customer_id ON orders (customer_id);
-- case-insensitive login lookup
CREATE UNIQUE INDEX customers_email_lower ON customers (lower(email));
-- "today's orders", written so the index can be used
CREATE INDEX orders_created_at ON orders (created_at);
SELECT id, total FROM orders
WHERE created_at >= date '2026-11-14' AND created_at < date '2026-11-15';
-- on a live production table: build without blocking writes
CREATE INDEX CONCURRENTLY order_items_product_id ON order_items (product_id);The index that’s there but not used
Tap the line with the bug.
CREATE INDEX orders_created_at ON orders (created_at);
-- admin page: all orders from a chosen day
SELECT id, customer_id, total
FROM orders
WHERE date(created_at) = '2026-11-14'
ORDER BY created_at;Hint: What is stored in the index: created_at, or date(created_at)?
The index holds created_at values. The condition asks about date(created_at), a value computed from each row, which the index doesn’t contain. So the database computes date(…) for all 40 million orders and compares each one: a full table scan, every time someone opens the page.
Ask about the column itself, as a range:
SELECT id, customer_id, total
FROM orders
WHERE created_at >= '2026-11-14'
AND created_at < '2026-11-15'
ORDER BY created_at;Now the database jumps to the first order of November 14 in the index and reads forward until November 15. The rows even come out already sorted, so ORDER BY costs nothing. Using >= and < (not BETWEEN) includes the whole day without counting midnight of the next day twice.
Deep diveIndex-only scans and covering indexesInterview favorite
An order history endpoint runs SELECT id, status, total FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 with an index on (customer_id, created_at). The plan is an Index Scan: 20 index entries, then 20 heap fetches on 20 different pages, often cold. At 3,000 requests per second, those random heap reads dominate.
A covering index stores the extra columns in the index leaves so the heap isn’t needed:
CREATE INDEX CONCURRENTLY orders_customer_recent
ON orders (customer_id, created_at DESC)
INCLUDE (status, total);INCLUDE (PostgreSQL 11+, SQL Server) adds payload columns that aren’t part of the sort key, so they don’t affect ordering or uniqueness. The plan becomes an Index Only Scan, with one caveat specific to PostgreSQL: MVCC visibility lives in the heap, so an index-only scan still visits the heap for pages not marked all-visible in the visibility map. EXPLAIN (ANALYZE) shows this as Heap Fetches: N. On a hot, frequently updated table, aggressive autovacuum keeps that number low; if it stays high, the covering index buys little.
Trade-offs to mention: wider indexes mean more memory and slower writes, and INCLUDE columns that change often (like status) generate new index entries on every update and prevent HOT updates. Cover the queries that are hot and stable, not every query.
- B-tree: depth 3–4, linked leaves for ranges and ordering; Index Scan → heap, Index Only Scan (visibility map), Bitmap Heap Scan for many rows.
- GIN for jsonb/arrays/full-text/trigram, GiST for ranges/geo, BRIN for append-only time series.
- Sargable predicates only: expression indexes (
lower(email)), ranges instead of::date, watch implicit casts. - Every index costs writes, WAL and HOT updates; drop unused ones (
idx_scan = 0, check replicas).CREATE INDEX CONCURRENTLYin production.
CREATE INDEX CONCURRENTLY orders_customer_recent
ON orders (customer_id, created_at DESC) INCLUDE (status, total);
CREATE INDEX ON customers (lower(email));
CREATE INDEX ON events USING brin (created_at);
CREATE INDEX ON products USING gin (attributes jsonb_path_ops);Check this part
Why does an index make WHERE customer_id = 42 fast?
There is an index on created_at. Can WHERE created_at::date = '2026-11-14' use it?
An Index Only Scan shows Heap Fetches: 9500 out of 10000 rows. Why?
Which index type fits WHERE attributes @> '{"color": "red"}' on a jsonb column?