A table is a pile of pages, in the order rows arrived. When you ask for one member’s workout history, Postgres has two choices: read every page and keep the matching rows, or look somewhere that already knows which pages to read. That second thing is an index.

The phone book version: the book is sorted by surname, so finding “Balona” takes a few flips. Finding everyone on a particular street means reading the whole book, because it isn’t sorted that way. An index is a second, sorted copy of one column (or a few), where every entry says which page the full row lives on.

Reading the whole pile

I filled a progress_entries table with 500,000 rows, spread across 5,000 members, and asked for one member’s history.

sql
EXPLAIN (ANALYZE) SELECT * FROM progress_entries WHERE member_id = 'member-42';
 Gather (actual rows=100 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   ->  Parallel Seq Scan on progress_entries (actual rows=33 loops=3)
         Filter: (member_id = 'member-42'::text)
         Rows Removed by Filter: 166633

Seq Scan is the phrase to learn. It means “read the table front to back”. Postgres split the work across three processes, each of which read a third of the pile and threw away 166,633 rows to keep 33. It found the 100 rows. It also read 33 MB to do it.

Adding the index

sql
CREATE INDEX progress_entries_member_id_idx ON progress_entries (member_id);

The index is 3.7 MB, a sorted list of member ids with row locations. The same query now reads:

 Bitmap Heap Scan on progress_entries (actual rows=100 loops=1)
   Recheck Cond: (member_id = 'member-42'::text)
   Heap Blocks: exact=100
   ->  Bitmap Index Scan on progress_entries_member_id_idx (actual rows=100 loops=1)
         Index Cond: (member_id = 'member-42'::text)

Index Scan, or here Bitmap Index Scan, is the other phrase. It found the 100 locations in the index, then fetched exactly those 100 pages from the table. Nothing was read and thrown away.

Those two words, Seq Scan versus Index Scan, answer most “why is this slow” questions before you read anything else in the plan.

The shape of the query is the shape of the index

The real query on a dashboard isn’t “all of Ana’s history”. It’s “Ana’s twenty most recent entries”:

sql
SELECT * FROM progress_entries
WHERE member_id = 'member-42'
ORDER BY completed_at DESC
LIMIT 20;

With the single-column index, Postgres finds her 100 rows and then has to sort them:

 Limit (actual rows=20 loops=1)
   ->  Sort (actual rows=20 loops=1)
         Sort Key: completed_at DESC
         Sort Method: top-N heapsort  Memory: 26kB
         ->  Bitmap Heap Scan on progress_entries (actual rows=100 loops=1)

Fine for 100 rows. Not fine for a member with 50,000. An index that is sorted the way the query wants removes the sort entirely:

sql
CREATE INDEX progress_entries_member_recent_idx
  ON progress_entries (member_id, completed_at DESC);
 Limit (actual rows=20 loops=1)
   ->  Index Scan using progress_entries_member_recent_idx on progress_entries (actual rows=20 loops=1)
         Index Cond: (member_id = 'member-42'::text)

Three lines. It walked to Ana’s section of the index, which is already in date order, took twenty entries, and stopped. Column order matters: (member_id, completed_at) can serve “this member, newest first”; (completed_at, member_id) cannot, because you’d have to scan every date to find one member.

When Postgres ignores your index

Ask for everyone except Ana:

sql
SELECT count(*) FROM progress_entries WHERE member_id <> 'member-42';
 Parallel Seq Scan on progress_entries (actual rows=166633 loops=3)
   Filter: (member_id <> 'member-42'::text)
   Rows Removed by Filter: 33

Back to a Seq Scan, with the index sitting right there. That’s not a failure. Nearly every row matches, so hopping from the index into the table 499,900 times would be slower than reading the table once. The planner chose. An index helps when it lets Postgres skip most of the table; when a query touches most of the table anyway, the index is dead weight.

Constraints are indexes

A primary key is a unique index. A UNIQUE constraint is a unique index. The partial unique index from my junction table post is an index that only contains active rows, which is why it’s tiny and why it enforces “one active per member” at the speed of a lookup. After adding one unique constraint to my test table:

 one_per_member_minute
 progress_entries_member_id_idx
 progress_entries_member_recent_idx
 progress_entries_pkey

Four indexes, and I only “created” two.

What they cost

Every index is a second copy that has to be updated on every insert, update, and delete of the columns it covers.

 table_size | all_indexes
------------+-------------
 33 MB      | 53 MB

My 33 MB table is carrying 53 MB of indexes. Each write to it now touches five structures instead of one. That’s the trade: reads get cheap, writes get more expensive, disk gets used twice.

The rule

Index the columns you filter or join on, in the order your queries use them, and no more. Check with EXPLAIN (ANALYZE): Seq Scan on a big table in a hot query is the smell, Index Scan is the cure, and a Sort under a Limit is a hint that the index has the wrong shape. Then find the ones nobody uses:

sql
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE idx_scan = 0;

An index with zero scans is pure write cost. Drop it.