← Building blocks

Index the columns you filter on

Latency & performancefundamental

A query scans the whole table to find a few rows.

Say it like this

Every query on the hot path filters or sorts on an indexed column, so each lookup is a tree seek of a few pages instead of a scan of the table.

Basic solution

Add an index on the lookup columns so the database can seek instead of scan. Composite indexes for multi-column filters, covering indexes to skip the table read.

B-treehash indexGIN / inverted indexEXPLAIN ANALYZE

B-tree seek versus table scan

A point lookup descends the tree in four or five page reads, almost all from memory. Without the index the same lookup reads every page of the table.

How it works

  1. An index is a separate structure, usually a B-tree, that stores the values of the indexed columns in sorted order, each with a pointer to the table row it came from. The table itself stays in whatever order rows were inserted.
  2. For WHERE alias = 'aB3xZ9' the planner walks down the tree from the root: each page holds a few hundred sorted keys, so with 6 billion rows the walk is 4 or 5 page reads, and the top pages are almost always already in memory.
  3. For a range condition or an ORDER BY on the indexed column, the planner finds the first matching entry and then reads the leaf pages in order, so the rows come out already sorted and no separate sort step is needed.
  4. A composite index on (user_id, created_at) sorts first by user, then by time within each user. "This user's newest links" becomes one seek to the user and a short forward read, instead of scanning everything.
  5. A covering index also stores every column the query returns, so the database can answer from the index alone and never fetch the table rows (an index-only scan).

What an index costs

  • Every INSERT, every UPDATE of an indexed column, and every DELETE must also update every index on the table. Ten indexes mean roughly ten extra writes per row change, plus the disk and memory for ten sorted copies of those columns.

Worked example

URL shortener on sharded Postgres

  • url_mapping has 6B rows at 500 B each ≈ 3 TB. Without an index on alias, a redirect would scan a shard: 300M rows per shard, seconds per lookup.
  • Primary key index on alias (7-char base62): B-tree depth 4 at 300M entries; a lookup is 4 page reads, 3 of them in the buffer cache, so under 1 ms on SSD.
  • "List my links" needs an index on (user_id, created_at DESC): seek to the user, read 20 entries in order, 1 or 2 pages.
  • Index size: alias index ≈ 300M × (7 B key + ~20 B overhead) ≈ 8 GB per shard, which fits in memory, so point reads rarely touch disk.
  • Write cost: 40 inserts/s × 2 indexes is negligible. On the click analytics table at 4,000 inserts/s, each extra index is 4,000 more index writes per second, so that table keeps one index and an append-only layout.

Variants and when each wins

B-tree (default)

  • A sorted tree that answers equality, range, prefix and ORDER BY queries. It wins for nearly every lookup, which is why it is the default in every relational database.

Hash index

  • A hash table from value to row pointer, equality lookups only, no ranges or ordering. It is slightly faster per lookup but rarely worth giving up ranges for.

GIN / inverted index

  • Maps each element inside a row (an array value, a JSONB key, a word in a text column) to the rows that contain it. It wins when a row holds many values and you search inside them; it is bigger and slower to update than a B-tree.

Partial index

  • Indexes only the rows that match a condition, such as WHERE status = 'pending'. It wins for queries that always include that condition on a rare value, because the index is tiny and every entry is a match.

Covering (INCLUDE) index

  • A B-tree that also carries extra columns the query returns, so the table is never read. It wins for the one or two hottest queries that return a few columns, at the cost of a wider index.

Recommendation: B-tree on the exact columns the hot queries filter and sort by, in selectivity order; partial and covering indexes for the one or two queries that dominate load.

Failure modes

Index not used

  • You notice EXPLAIN shows a sequential scan even though an index exists on the column. It happens because the query wraps the column in a function (lower(email)), compares it against a different type, uses a LIKE with a leading wildcard, or the condition matches so many rows that scanning the table is cheaper. Fix it by indexing the expression, casting the parameter to the column type, or restructuring the condition so it matches the index.

Write throughput collapses

  • You notice inserts get slower as the table grows. It happens because each insert updates too many indexes, or because random keys such as UUIDv4 land on random pages and split them across the whole tree. Fix it by dropping indexes the usage statistics show are never used, and by using time-ordered ids so inserts append to one end of the tree.

Index bloat

  • You notice the index is much larger than the data it indexes and lookups touch more pages than they should. It happens because heavy updates and deletes leave dead entries behind. Fix it with REINDEX or tuned autovacuum, and by partitioning old data away so it stops being updated.

Wrong column order

  • You notice a composite index exists but the query still scans. It happens because the query filters only on the second column, and a composite index can only be searched from its first column. Fix it by putting the column every query filters on first, or adding a second index for the other query.

Stale statistics

  • You notice the planner picks a bad plan right after a bulk load. It happens because the planner's row estimates come from statistics gathered before the load, so it misjudges how many rows will match. Fix it by running ANALYZE after any large change and comparing estimated with actual rows in EXPLAIN ANALYZE.

Interviewer follow-ups

Answer out loud before you open each one.

How do you decide which columns to index?

Start from the queries, not the schema: take the top queries by total time, and index the columns in their WHERE, JOIN and ORDER BY clauses, with the most selective column first in composites. Then confirm with EXPLAIN ANALYZE that each uses its index.

Why is a UUIDv4 primary key bad for a large table?

Random keys insert into random positions in the B-tree, so every insert touches a random page, causes page splits and defeats the buffer cache. Time-ordered ids such as UUIDv7 or Snowflake append to the right-hand edge and keep the tree compact.

What does an index-only scan need?

Every column the query reads must be in the index, including those in SELECT, and the row-visibility information must be current so the database can trust the index without checking the table. In Postgres that means a recent VACUUM.

How would you add an index to a 3 TB table in production?

Build it concurrently so the table is not locked, during a low-traffic window, one shard at a time, watching replication lag and I/O. Expect it to take hours and to double write I/O while it runs.

Connections

Built on
B-tree · Bitmap index · Inverted index
Pairs with
Read the query plan · Index selective columns first · Generate unique ids without a central counter · Page results with a cursor
Pulls against
Know your write amplification