Vineet Ganti
Indexes and Query Plans: Reading EXPLAIN the Way the Planner Thinks
All posts

Data Engineering/Database Engineering · Part 3 of 14

·29 min read

Indexes and Query Plans: Reading EXPLAIN the Way the Planner Thinks

What an index really buys you, how to read EXPLAIN, why the planner flips between index, bitmap and sequential scans, how composite indexes work, and why the course's leftmost-column rule changed in Postgres 18. Every plan here came from a real run.

DatabasesPostgreSQLIndexingPerformance

Post 2 ended with a number worth remembering: one row by primary key touched 3 pages, and a sum over the same table touched 934. An index is the difference between those two. This post is about what indexes really do, how to read the plan a database chooses, and how to tell when an index won't help.

It's also where re-running the course paid off the most. Two rules I'd copied into my notes turned out to be out of date on Postgres 18, and one index in the course's own demo made a query slower.

#What an index is

An index is a structure, separate from the table, that's sorted by the columns you chose and stores a pointer to each row. Think of the index at the back of a textbook: you find the word, then go straight to the page.

Most indexes are B-trees, covered in post 5. For now it's enough that a B-tree finds a value in a few page reads, however large the table.

The course starts with a table of a million employees with random names. Postgres creates an index for the primary key automatically, so id has one and name doesn't. Here's the difference, with the first plans of the series:

✅ ran here · PostgreSQL 18.6 · one million rows
\d employees
                            Table "public.employees"
 Column |  Type   | Collation | Nullable |                Default                
--------+---------+-----------+----------+---------------------------------------
 id     | integer |           | not null | nextval('employees_id_seq'::regclass)
 name   | text    |           |          | 
Indexes:
    "employees_pkey" PRIMARY KEY, btree (id)

EXPLAIN ANALYZE SELECT id FROM employees WHERE id = 2000;
                                                            QUERY PLAN                                                            
----------------------------------------------------------------------------------------------------------------------------------
 Index Only Scan using employees_pkey on employees  (cost=0.42..4.44 rows=1 width=4) (actual time=0.070..0.071 rows=1.00 loops=1)
   Index Cond: (id = 2000)
   Heap Fetches: 0
   Index Searches: 1
   Buffers: shared hit=4
 Planning:
   Buffers: shared hit=14
 Planning Time: 0.147 ms
 Execution Time: 0.139 ms
(9 rows)

EXPLAIN ANALYZE SELECT name FROM employees WHERE id = 2000;
                                                         QUERY PLAN                                                          
-----------------------------------------------------------------------------------------------------------------------------
 Index Scan using employees_pkey on employees  (cost=0.42..8.44 rows=1 width=6) (actual time=0.006..0.006 rows=1.00 loops=1)
   Index Cond: (id = 2000)
   Index Searches: 1
   Buffers: shared hit=4
 Planning:
   Buffers: shared hit=3
 Planning Time: 0.033 ms
 Execution Time: 0.026 ms
(8 rows)

EXPLAIN ANALYZE SELECT id FROM employees WHERE name = 'Zs';
                                                        QUERY PLAN                                                         
---------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..11334.23 rows=9 width=4) (actual time=21.607..27.521 rows=0.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=5125
   ->  Parallel Seq Scan on employees  (cost=0.00..10333.33 rows=4 width=4) (actual time=15.074..15.076 rows=0.00 loops=3)
         Filter: (name = 'Zs'::text)
         Rows Removed by Filter: 333333
         Buffers: shared hit=5125
 Planning Time: 0.019 ms
 Execution Time: 27.532 ms
(10 rows)

Three queries and three different plans:

  1. SELECT id ... WHERE id = 2000 is an Index Only Scan: the answer is in the index, and the table was never touched.
  2. SELECT name ... WHERE id = 2000 is an Index Scan: the index found the row, then one trip to the heap fetched name.
  3. ... WHERE name = 'Zs' has no index to use, so it's a Parallel Seq Scan: three processes read all 5,125 pages between them, to find nothing. That took 27 ms instead of 0.1 ms.

Now index name, and also try a pattern:

✅ ran here · PostgreSQL 18.6
EXPLAIN ANALYZE SELECT id, name FROM employees WHERE name = 'Zs';
                                                        QUERY PLAN                                                         
---------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on employees  (cost=4.50..43.30 rows=10 width=10) (actual time=0.097..0.098 rows=0.00 loops=1)
   Recheck Cond: (name = 'Zs'::text)
   Buffers: shared read=3
   ->  Bitmap Index Scan on employees_name  (cost=0.00..4.50 rows=10 width=0) (actual time=0.091..0.091 rows=0.00 loops=1)
         Index Cond: (name = 'Zs'::text)
         Index Searches: 1
         Buffers: shared read=3
 Planning:
   Buffers: shared hit=84 read=1
 Planning Time: 0.997 ms
 Execution Time: 0.177 ms
(11 rows)

EXPLAIN ANALYZE SELECT id, name FROM employees WHERE name LIKE '%Zs%';
                                                         QUERY PLAN                                                          
-----------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..11341.33 rows=90 width=10) (actual time=19.910..22.957 rows=0.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=5124
   ->  Parallel Seq Scan on employees  (cost=0.00..10332.33 rows=38 width=10) (actual time=16.356..16.357 rows=0.00 loops=3)
         Filter: (name ~~ '%Zs%'::text)
         Rows Removed by Filter: 333333
         Buffers: shared hit=5124
 Planning:
   Buffers: shared hit=2
 Planning Time: 0.038 ms
 Execution Time: 22.972 ms
(12 rows)

The exact match fell from 27 ms to 0.2 ms. LIKE '%Zs%' went back to scanning everything, even with the index in place, because the index is sorted from the first character. A pattern that starts with a wildcard gives it nowhere to start. There's a way out for this particular problem, which the course doesn't reach: a trigram index breaks strings into three-letter pieces, so any substring can be looked up.

✅ ran here · PostgreSQL 18.6
EXPLAIN ANALYZE SELECT id, name FROM employees WHERE name LIKE '%abc%';
                                                            QUERY PLAN                                                             
-----------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on employees  (cost=17.54..342.88 rows=90 width=10) (actual time=0.459..3.241 rows=825.00 loops=1)
   Recheck Cond: (name ~~ '%abc%'::text)
   Heap Blocks: exact=773
   Buffers: shared hit=777
   ->  Bitmap Index Scan on employees_name_trgm  (cost=0.00..17.52 rows=90 width=0) (actual time=0.400..0.400 rows=825.00 loops=1)
         Index Cond: (name ~~ '%abc%'::text)
         Index Searches: 1
         Buffers: shared hit=4
 Planning:
   Buffers: shared hit=85
 Planning Time: 1.682 ms
 Execution Time: 3.363 ms
(12 rows)

#Reading EXPLAIN

EXPLAIN shows the plan without running the query. EXPLAIN ANALYZE runs it and adds what really happened. This is one line of a plan:

text
Seq Scan on grades  (cost=0.00..16370.00 rows=1000000 width=22)
                          │       │          │           └ average bytes per row
                          │       │          └ rows the planner expects
                          │       └ estimated cost to return all rows
                          └ estimated cost before the first row

The two cost numbers matter, and the first is easy to overlook. It's the startup cost: the work done before the first row can come out. A sort has to read everything before it can output anything, so its startup cost is huge:

✅ ran here · PostgreSQL 18.6
EXPLAIN SELECT * FROM grades;
                           QUERY PLAN                            
-----------------------------------------------------------------
 Seq Scan on grades  (cost=0.00..16370.00 rows=1000000 width=22)
(1 row)

EXPLAIN SELECT * FROM grades ORDER BY g;
                              QUERY PLAN                               
-----------------------------------------------------------------------
 Sort  (cost=136537.84..139037.84 rows=1000000 width=22)
   Sort Key: g
   ->  Seq Scan on grades  (cost=0.00..16370.00 rows=1000000 width=22)
(3 rows)

EXPLAIN SELECT * FROM grades ORDER BY g LIMIT 10;
                                        QUERY PLAN                                         
-------------------------------------------------------------------------------------------
 Limit  (cost=20540.71..20541.88 rows=10 width=22)
   ->  Gather Merge  (cost=20540.71..137007.31 rows=1000001 width=22)
         Workers Planned: 2
         ->  Sort  (cost=19540.69..20582.36 rows=416667 width=22)
               Sort Key: g
               ->  Parallel Seq Scan on grades  (cost=0.00..10536.67 rows=416667 width=22)
(6 rows)

A plain scan can start at once (0.00). The ORDER BY pushed startup to 136,537, nearly the whole total. With LIMIT 10 the plan changed shape entirely, because keeping the top 10 is far cheaper than sorting a million rows.

What to look for in a plan, in order:

Look atWhy
Estimated rows against actual rowsA big gap means stale or misleading statistics, and everything planned on top of it may be wrong
The scan type at the bottomThe biggest single decision the planner made
Buffers: shared hit=… read=…Pages touched, the most honest measure of work
Rows Removed by FilterRows read and thrown away, a sign an index could help
Heap FetchesIndex-only scans that weren't really index-only

Ignore tiny differences in time. The course keeps repeating this and it's right: timings depend on caches and hardware. Plans and pages are what to compare.

#Three ways to read a table

The planner's main decision is how to get the rows. Think of it as a spectrum:

An Index Scan follows each pointer as it finds it. If matching rows are scattered, that's a jump to a different page for every row, and the same page may be read many times.

A Bitmap Heap Scan fixes that with a two-phase plan:

A Seq Scan reads every page in order. That sounds like the bad option, but sequential reading is fast and needs no index pages at all. If you want most of the table anyway, jumping through an index is pure overhead.

#Watching the plan flip

I wanted to see the switch-over points rather than take them on trust. So I ran one query on a million-row table with an index on a randomly ordered column, and widened its WHERE clause from 0.001% of rows to 100%. At each width I turned off the other plans to force each of the three, and asked the planner for its estimate:

At 100% of rows matching: Index Scan 70,872 · Bitmap Heap Scan 42,692 · Seq Scan 25,310 (the planner's pick) ✅ measured on PostgreSQL 18.6

The lowest line at any point is what the planner picks. Index Scan and Bitmap are nearly tied at the far left, Bitmap wins through the middle, and Seq Scan is almost flat, because it reads the same pages however many rows match. It wins somewhere between 30% and 50% here.

Estimates are only half the story. Here's what each forced plan really took:

At 100% of rows matching: Index Scan 428 ms · Bitmap Heap Scan 87.1 ms · Seq Scan 55.6 ms (the planner's pick) ✅ measured on PostgreSQL 18.6

The shape matches, with one big difference: the Index Scan is much worse than the bitmap at higher shares, reaching 428 ms where a Seq Scan takes 56 ms. That's one random page jump per row, a million times.

The box below is real Postgres, in your browser, with 100,000 rows. Run each preset and read the first line of the plan:

Watch the plan changeruns in your browser
100,000 rows with an index on x. Each preset asks for a different share of the table. Read the top line of each plan.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

The last preset shows a classic mistake: x + 1 = 501 can't use the index on x, because the index stores x, not x + 1. Write x = 500 instead.

#When an index isn't worth it

A student found that a query on a 7-row table ignored its index:

✅ ran here · PostgreSQL 18.6
EXPLAIN SELECT * FROM tiny WHERE id = 3;
                     QUERY PLAN                      
-----------------------------------------------------
 Seq Scan on tiny  (cost=0.00..1.09 rows=1 width=10)
   Filter: (id = 3)
(2 rows)

SELECT relpages FROM pg_class WHERE relname = 'tiny';
 relpages 
----------
        1
(1 row)

The whole table is one page. An index lookup would read at least one index page and then that same heap page. The Seq Scan reads just the one, so it's the right plan, and it's a good reminder that "Seq Scan" isn't a bug by itself.

#Index scans, index-only scans and INCLUDE

The course builds this up one step at a time on a grades table. I ran the same steps on a million rows:

✅ ran here · PostgreSQL 18.6 · from no index to a covering index
EXPLAIN ANALYZE SELECT name FROM grades WHERE id = 7;
                                                       QUERY PLAN                                                       
------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..12578.43 rows=1 width=14) (actual time=0.463..19.323 rows=1.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=6370
   ->  Parallel Seq Scan on grades  (cost=0.00..11578.33 rows=1 width=14) (actual time=7.286..12.477 rows=0.33 loops=3)
         Filter: (id = 7)
         Rows Removed by Filter: 333333
         Buffers: shared hit=6370
 Planning:
   Buffers: shared hit=29
 Planning Time: 0.339 ms
 Execution Time: 19.359 ms
(12 rows)

CREATE INDEX id_idx ON grades (id);

EXPLAIN ANALYZE SELECT name FROM grades WHERE id = 7;
                                                    QUERY PLAN                                                     
-------------------------------------------------------------------------------------------------------------------
 Index Scan using id_idx on grades  (cost=0.42..8.44 rows=1 width=14) (actual time=0.034..0.035 rows=1.00 loops=1)
   Index Cond: (id = 7)
   Index Searches: 1
   Buffers: shared hit=1 read=3
 Planning:
   Buffers: shared hit=19 read=1
 Planning Time: 0.954 ms
 Execution Time: 0.055 ms
(8 rows)

EXPLAIN ANALYZE SELECT id FROM grades WHERE id = 7;
                                                      QUERY PLAN                                                       
-----------------------------------------------------------------------------------------------------------------------
 Index Only Scan using id_idx on grades  (cost=0.42..4.44 rows=1 width=4) (actual time=0.014..0.014 rows=1.00 loops=1)
   Index Cond: (id = 7)
   Heap Fetches: 0
   Index Searches: 1
   Buffers: shared hit=4
 Planning Time: 0.018 ms
 Execution Time: 0.018 ms
(7 rows)

DROP INDEX id_idx;

CREATE INDEX id_idx ON grades (id) INCLUDE (name);

VACUUM grades;

EXPLAIN ANALYZE SELECT name FROM grades WHERE id = 7;
                                                       QUERY PLAN                                                       
------------------------------------------------------------------------------------------------------------------------
 Index Only Scan using id_idx on grades  (cost=0.42..4.44 rows=1 width=14) (actual time=0.041..0.041 rows=1.00 loops=1)
   Index Cond: (id = 7)
   Heap Fetches: 0
   Index Searches: 1
   Buffers: shared hit=1 read=3
 Planning:
   Buffers: shared hit=3
 Planning Time: 0.100 ms
 Execution Time: 0.059 ms
(9 rows)

EXPLAIN ANALYZE SELECT g FROM grades WHERE id = 7;
                                                    QUERY PLAN                                                    
------------------------------------------------------------------------------------------------------------------
 Index Scan using id_idx on grades  (cost=0.42..8.44 rows=1 width=4) (actual time=0.004..0.005 rows=1.00 loops=1)
   Index Cond: (id = 7)
   Index Searches: 1
   Buffers: shared hit=4
 Planning:
   Buffers: shared hit=3
 Planning Time: 0.032 ms
 Execution Time: 0.009 ms
(8 rows)

Follow the plans in order:

  1. No index: Parallel Seq Scan, 6,370 pages, 19 ms.
  2. Index on id: an Index Scan at 0.06 ms, because name still needs a trip to the heap.
  3. Asking only for id: an Index Only Scan. Fast, and a slightly silly query, since you already knew the answer.
  4. INCLUDE (name): now name lives in the index too, and the useful query is index-only.
  5. Asking for g: back to an Index Scan, because g isn't in the index.

In CREATE INDEX ... (id) INCLUDE (name), id is a key column: the tree is sorted by it, and you can search by it. name is a non-key column: it's only carried along in the leaf pages, so you can't search by it. It makes the index larger, which means more pages to read, so include a column only when you know the queries that need it.

#The index that made things worse

The course's students demo has a wide table, and a query on a range of grades. Its result surprised me, so here's the whole thing:

✅ ran here · PostgreSQL 18.6 · a wide table, one million rows
EXPLAIN (ANALYZE, BUFFERS) SELECT id, g FROM students WHERE g > 80 AND g < 95 ORDER BY g;
                                                              QUERY PLAN                                                               
---------------------------------------------------------------------------------------------------------------------------------------
 Gather Merge  (cost=36230.17..52443.12 rows=139207 width=8) (actual time=31.281..65.635 rows=140247.00 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   Buffers: shared hit=24465
   ->  Sort  (cost=35230.15..35375.16 rows=58003 width=8) (actual time=27.976..32.501 rows=46749.00 loops=3)
         Sort Key: g
         Sort Method: quicksort  Memory: 2714kB
         Buffers: shared hit=24465
         Worker 0:  Sort Method: quicksort  Memory: 2618kB
         Worker 1:  Sort Method: quicksort  Memory: 2564kB
         ->  Parallel Seq Scan on students  (cost=0.00..30641.00 rows=58003 width=8) (actual time=0.111..22.746 rows=46749.00 loops=3)
               Filter: ((g > 80) AND (g < 95))
               Rows Removed by Filter: 286584
               Buffers: shared hit=24391
 Planning:
   Buffers: shared hit=70
 Planning Time: 0.369 ms
 Execution Time: 70.051 ms
(18 rows)

CREATE INDEX students_g ON students (g);

EXPLAIN (ANALYZE, BUFFERS) SELECT id, g FROM students WHERE g > 80 AND g < 95 ORDER BY g;
                                                               QUERY PLAN                                                                
-----------------------------------------------------------------------------------------------------------------------------------------
 Sort  (cost=42183.46..42531.48 rows=139207 width=8) (actual time=66.713..72.795 rows=140247.00 loops=1)
   Sort Key: g
   Sort Method: external merge  Disk: 2480kB
   Buffers: shared hit=24341 read=121, temp read=310 written=311
   ->  Bitmap Heap Scan on students  (cost=1907.30..28386.40 rows=139207 width=8) (actual time=7.349..46.980 rows=140247.00 loops=1)
         Recheck Cond: ((g > 80) AND (g < 95))
         Heap Blocks: exact=24340
         Buffers: shared hit=24341 read=121
         ->  Bitmap Index Scan on students_g  (cost=0.00..1872.49 rows=139207 width=0) (actual time=5.239..5.241 rows=140247.00 loops=1)
               Index Cond: ((g > 80) AND (g < 95))
               Index Searches: 1
               Buffers: shared hit=1 read=121
 Planning:
   Buffers: shared hit=27 read=6
 Planning Time: 1.091 ms
 Execution Time: 77.020 ms
(16 rows)

DROP INDEX students_g;

CREATE INDEX students_g ON students (g) INCLUDE (id);

VACUUM students;

EXPLAIN (ANALYZE, BUFFERS) SELECT id, g FROM students WHERE g > 80 AND g < 95 ORDER BY g;
                                                                QUERY PLAN                                                                 
-------------------------------------------------------------------------------------------------------------------------------------------
 Index Only Scan using students_g on students  (cost=0.42..4316.56 rows=139207 width=8) (actual time=0.012..13.148 rows=140247.00 loops=1)
   Index Cond: ((g > 80) AND (g < 95))
   Heap Fetches: 0
   Index Searches: 1
   Buffers: shared hit=2 read=386
 Planning:
   Buffers: shared hit=14 read=5
 Planning Time: 0.107 ms
 Execution Time: 16.885 ms
(9 rows)

SELECT pg_size_pretty(pg_relation_size('students')) AS table_size, pg_size_pretty(pg_relation_size('students_g')) AS index_size;
 table_size | index_size 
------------+------------
 191 MB     | 21 MB
(1 row)
SetupPlanPagesTime
No indexParallel Seq Scan, then sort24,46570 ms
Index on gBitmap Heap Scan, then sort24,46277 ms
Index on g INCLUDE (id)Index Only Scan38817 ms

The plain index made this query slower. Rows with grades from 81 to 94 are 14% of the table, spread evenly, so nearly every page holds one: the bitmap had to visit 24,340 of them anyway. It also lost parallelism, and its sort spilled to disk (external merge Disk: 2480kB). The course saw a small win here (21 s down to 17 s) on a bigger table, and I saw a small loss. Either way the index barely mattered, because the query still had to read the table. The covering index won because it didn't: 388 pages of a 21 MB index, instead of a 191 MB table.

The real lesson is to measure work rather than assume. An index only helps if it reduces the pages you read.

#Why an index-only scan can still read the table

An index entry doesn't say whether its row version is visible to your transaction. That information is in the row, because of MVCC. Without help, an index-only scan would have to check the heap for every row.

The help is the visibility map: one bit per heap page, meaning "every row here is visible to everyone".

Request or acknowledgmentDataMetadata

This explains a question that came up in the Q&A: why doesn't a query go index-only right after a big insert? Because nothing has set those bits yet. VACUUM sets them, and any write clears them. Here it is with autovacuum turned off, so the effect is clean:

✅ ran here · PostgreSQL 18.6
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM fresh WHERE id < 50000;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=222 read=138
   ->  Index Only Scan using fresh_id on fresh (actual rows=49999.00 loops=1)
         Index Cond: (id < 50000)
         Heap Fetches: 49999
         Index Searches: 1
         Buffers: shared hit=222 read=138
 Planning:
   Buffers: shared hit=67 read=1
(9 rows)

VACUUM fresh;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM fresh WHERE id < 50000;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=139
   ->  Index Only Scan using fresh_id on fresh (actual rows=49999.00 loops=1)
         Index Cond: (id < 50000)
         Heap Fetches: 0
         Index Searches: 1
         Buffers: shared hit=139
 Planning:
   Buffers: shared hit=4
(9 rows)

UPDATE fresh SET id = id WHERE id < 5000;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM fresh WHERE id < 50000;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   Buffers: shared hit=10152
   ->  Index Only Scan using fresh_id on fresh (actual rows=49999.00 loops=1)
         Index Cond: (id < 50000)
         Heap Fetches: 10197
         Index Searches: 1
         Buffers: shared hit=10152
(7 rows)

Look at Heap Fetches: 49,999 before VACUUM, 0 after, and 10,197 once I'd touched 4,999 rows, since each update cleared the bit for its page. The plan's name said Index Only Scan the whole time, so this line is the one to trust. (In the lecture the planner chose a bitmap scan here. Plans differ by version and data, and the Q&A says so. The reason doesn't change.)

#Combining indexes

Real queries filter on more than one column. The course tests three index layouts against the query shapes a backend actually sends. Here are the real results, on a million rows. Pick a layout, then click a query to read its plan:

QueryPlanPages touchedTime
Bitmap Heap Scan + Bitmap Index Scan i_a4,5453.4 ms
Seq Scan20 ms
Bitmap Heap Scan + Bitmap Index Scan i_b4,6143.9 ms
Bitmap Heap Scan + BitmapAnd + Bitmap Index Scan i_b + Bitmap Index Scan i_a1260.8 ms
Bitmap Heap Scan + BitmapOr + Bitmap Index Scan i_a + Bitmap Index Scan i_b5,3055.7 ms
SELECT c FROM test WHERE a = 70
Bitmap Heap Scan on test  (cost=112.89..5752.94 rows=9867 width=4) (actual rows=10092.00 loops=1)
  Recheck Cond: (a = 70)
  Heap Blocks: exact=4534
  Buffers: shared hit=4545
  ->  Bitmap Index Scan on i_a  (cost=0.00..110.43 rows=9867 width=0) (actual rows=10092.00 loops=1)
        Index Cond: (a = 70)
        Index Searches: 1
        Buffers: shared hit=11
Execution Time: 3.968 ms
✅ measured on PostgreSQL 18.6, warm cache, one million rows

With separate indexes, an AND query scans both and combines the bitmaps before touching the table:

A composite index does better on a AND b: one descent to the right place, 107 pages, and 0.1 ms. It's the best layout if your queries filter on both columns together.

#The leftmost-column rule, and what changed

A composite index is sorted by the first column, then by the second within each value of the first, like a phone book sorted by surname, then first name.

So a search on a is a range, and a AND b is a point. The rule I copied from the lecture is that a search on b alone can't use the index at all, and falls back to a full scan, as does a OR b.

There's a condition. The docs say this is chosen only when the leading column has few distinct values. Here's the same query on two tables, one with 10 values of a, and one with a million:

✅ ran here · PostgreSQL 18.6
SET max_parallel_workers_per_gather = 0;

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT c FROM few WHERE b = 40;
                           QUERY PLAN                           
----------------------------------------------------------------
 Bitmap Heap Scan on few (actual rows=956.00 loops=1)
   Recheck Cond: (b = 40)
   Heap Blocks: exact=886
   Buffers: shared hit=911 read=17
   ->  Bitmap Index Scan on few_ab (actual rows=956.00 loops=1)
         Index Cond: (b = 40)
         Index Searches: 12
         Buffers: shared hit=25 read=17
 Planning:
   Buffers: shared hit=73
(10 rows)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT c FROM many WHERE b = 40;
                   QUERY PLAN                   
------------------------------------------------
 Seq Scan on many (actual rows=1030.00 loops=1)
   Filter: (b = 40)
   Rows Removed by Filter: 998970
   Buffers: shared hit=5406
 Planning:
   Buffers: shared hit=28
(6 rows)

With 10 distinct values: Index Searches: 12, using the index. With a million distinct values it's a Seq Scan, exactly as the old rule says. So the practical advice survives: put the column you filter on most at the left, and don't rely on skip scan for a column with many values.

Try the rule yourself. The last preset adds the separate index on b, which is the course's final layout:

The leftmost column ruleruns in your browser
A composite index on (a, b). Which of these can use it? Edit the WHERE clause, or create another index and run them again.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

The last layout is the engineering compromise: if some queries filter on b alone, (a, b) plus (b) serves every shape. Each extra index slows every write, so build this for queries you really run.

#How the planner decides

The planner doesn't look at your data when it plans. It reads statistics: approximate counts and common values, gathered by ANALYZE. Those give three broad options for a query with two conditions:

OptionChosen when
Use both indexes, combine the resultsBoth match a medium number of rows
Use one index, filter the rest on the fetched rowsOne is far more selective, and the condition is AND
Use no index, scan and filterTogether they match a large share of the table

Searching an index isn't free, so a second index has to earn its cost. With a primary key in an AND, the database nearly always uses just that.

#Selectivity depends on the value

An index's usefulness isn't a property of the column alone. A table where nearly every customer lives in California, and one lives in Florida:

✅ ran here · PostgreSQL 18.6
SET max_parallel_workers_per_gather = 0;

EXPLAIN SELECT * FROM customers WHERE state = 'California';
                             QUERY PLAN                             
--------------------------------------------------------------------
 Seq Scan on customers  (cost=0.00..17906.00 rows=1000000 width=15)
   Filter: (state = 'California'::text)
(2 rows)

EXPLAIN SELECT * FROM customers WHERE state = 'Florida';
                                    QUERY PLAN                                    
----------------------------------------------------------------------------------
 Index Scan using customers_state on customers  (cost=0.42..4.44 rows=1 width=15)
   Index Cond: (state = 'Florida'::text)
(2 rows)

SELECT most_common_vals, most_common_freqs FROM pg_stats WHERE tablename = 'customers' AND attname = 'state';
 most_common_vals | most_common_freqs 
------------------+-------------------
 {California}     | {1}
(1 row)

Same column, same index, opposite plans. The statistics at the end show why: Postgres knows California covers almost everything, so it scans, and treats anything else as rare, so it uses the index. A column with few distinct values is a poor index candidate only when you search for the common ones.

#Stale statistics

The course's war story: load millions of rows into a fresh table, query it at once, and the planner still believes the table holds 3 rows, so it does something foolish. To test it, I gathered statistics on 3 rows, loaded a million, and queried before ANALYZE:

✅ ran here · PostgreSQL 18.6
EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'shipped';
                                                          QUERY PLAN                                                           
-------------------------------------------------------------------------------------------------------------------------------
 Index Scan using orders_status on orders  (cost=0.41..4.43 rows=1 width=8) (actual time=0.033..78.331 rows=999990.00 loops=1)
   Index Cond: (status = 'shipped'::text)
   Index Searches: 1
   Buffers: shared hit=6191
 Planning:
   Buffers: shared hit=85
 Planning Time: 0.308 ms
 Execution Time: 102.695 ms
(8 rows)

ANALYZE orders;

EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'shipped';
                                                    QUERY PLAN                                                     
-------------------------------------------------------------------------------------------------------------------
 Seq Scan on orders  (cost=0.00..17906.04 rows=999970 width=11) (actual time=0.015..73.758 rows=999990.00 loops=1)
   Filter: (status = 'shipped'::text)
   Rows Removed by Filter: 13
   Buffers: shared hit=5406
 Planning:
   Buffers: shared hit=25
 Planning Time: 0.151 ms
 Execution Time: 98.072 ms
(8 rows)

EXPLAIN ANALYZE SELECT * FROM orders WHERE status = 'held';
                                                         QUERY PLAN                                                         
----------------------------------------------------------------------------------------------------------------------------
 Index Scan using orders_status on orders  (cost=0.42..9.00 rows=33 width=11) (actual time=0.018..0.029 rows=10.00 loops=1)
   Index Cond: (status = 'held'::text)
   Index Searches: 1
   Buffers: shared hit=13
 Planning Time: 0.054 ms
 Execution Time: 0.037 ms
(6 rows)

The first plan expected 1 row and got 999,990. That's the trap, but it went the other way from the story, which says the planner would do a full scan. Here it chose an Index Scan, because it believed few rows matched. On this data the damage was small, since the rows were in index order and in memory. After ANALYZE the estimates were right, and it chose a Seq Scan for shipped and the index for held.

The direction doesn't matter much. When estimates are wrong, plans are wrong. After a bulk load, run ANALYZE yourself instead of waiting for autovacuum.

#Hints

Some databases let you overrule the planner. MySQL's FORCE INDEX does it here, and notice how the estimate worsens from 1 row to 100:

✅ ran here · MySQL 8.4.13
EXPLAIN SELECT id FROM t WHERE a = 1 AND b = 1;
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | t     | NULL       | ref  | i_a,i_b       | i_b  | 5       | const |    1 |    10.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.02 sec)

EXPLAIN SELECT id FROM t FORCE INDEX (i_a) WHERE a = 1 AND b = 1;
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | t     | NULL       | ref  | i_a           | i_a  | 5       | const |  100 |     0.10 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

Oracle and SQL Server have hints too. 📘 Postgres has no built-in hints. The pg_hint_plan extension adds them. Use them only if you know something the statistics can't, because a hint stays in the code long after the data has changed.

#Seek or scan?

One article in the course is about two operations on the same index, in SQL Server's terms. A seek starts at the root and walks down to a value. A scan walks along the leaf pages. Fetching three distant ids is three seeks, and fetching a range is one seek followed by a scan. Postgres 18 finally shows this directly in Index Searches:

✅ ran here · PostgreSQL 18.6
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT g FROM grades WHERE id IN (1, 5003, 9000);
                            QUERY PLAN                             
-------------------------------------------------------------------
 Index Scan using grades_pkey on grades (actual rows=3.00 loops=1)
   Index Cond: (id = ANY ('{1,5003,9000}'::integer[]))
   Index Searches: 3
   Buffers: shared hit=12
 Planning:
   Buffers: shared hit=106
(6 rows)

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT g FROM grades WHERE id BETWEEN 1 AND 9000;
                              QUERY PLAN                              
----------------------------------------------------------------------
 Index Scan using grades_pkey on grades (actual rows=9000.00 loops=1)
   Index Cond: ((id >= 1) AND (id <= 9000))
   Index Searches: 1
   Buffers: shared hit=67
 Planning:
   Buffers: shared hit=18
(6 rows)

Three ids: 3 searches and 12 pages. A range of 9,000 ids: 1 search and 67 pages. Neither is better in general. If values are far apart, separate seeks avoid reading pages in between. If they're close, one seek plus a scan avoids starting again from the root.

#What a non-unique index stores

A student asked how an index stores duplicates, for example a project column with 10 distinct values across a million rows. The simple answer is one entry per row, with the value repeated. The course mentions that newer versions avoid repeating it, which is easy to measure:

✅ ran here · PostgreSQL 18.6
CREATE INDEX unique_ish ON tickets (id);

CREATE INDEX dedup_on ON tickets (project);

CREATE INDEX dedup_off ON tickets (project) WITH (deduplicate_items = off);

SELECT indexrelname AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_stat_user_indexes ORDER BY pg_relation_size(indexrelid) DESC;
   index    |  size   
------------+---------
 dedup_off  | 21 MB
 unique_ish | 21 MB
 dedup_on   | 6800 kB
(3 rows)

With deduplication off, the index on 10 distinct values is as big as an index on unique ids: 21 MB. With the default, added in Postgres 13, each value is stored once followed by a list of row addresses: 6.8 MB.

#Indexes aren't free

Every index slows every write. An INSERT must update all of them, and an UPDATE can too, which post 14 measures. Indexes also compete for memory: an index that fits in the buffer pool is fast, and one that doesn't means more I/O.

A student asked whether to create and drop indexes with non-key columns for short-term use. The course's answer is that non-key indexes are common in production, and that each should be judged by how often its query runs against what it costs to keep. For a report that runs once, build the index and then drop it. Building it on a big table is itself a heavy operation, though, as the next section shows.

#Adding an index to a live table

Can you write to a table while an index is being built? On Postgres, by default, no:

CREATE INDEX blocks writes✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
The transaction holds the index build open, so the lock is easy to see. A real build on a big table holds it for as long as the build takes.
orders, seen from a third connection
rows
1000
Step 1 of 5

The build reads the whole table, and a row changed behind it would be missed, so CREATE INDEX takes a lock that blocks writes. Reads continue. On a production table that means an outage lasting as long as the build. The answer is CREATE INDEX CONCURRENTLY:

CONCURRENTLY doesn't block, but it does wait✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
Session A opens a transaction and does some work.
orders, seen from a third connection
rows
1000
Step 1 of 5

Writers aren't blocked. Instead the build waits for them, and does more work. The docs describe the phases:

The course sketches how it would build this itself, as a thought experiment, and gets the idea right: build from a snapshot, then catch up. It can also fail, and that leaves something behind:

✅ ran here · PostgreSQL 18.6 · a failed concurrent build
CREATE UNIQUE INDEX CONCURRENTLY users_email ON users (email);
ERROR:  could not create unique index "users_email"
DETAIL:  Key (email)=(a@example.com) is duplicated.

\d users
               Table "public.users"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 id     | integer |           |          | 
 email  | text    |           |          | 
Indexes:
    "users_email" UNIQUE, btree (email) INVALID

DROP INDEX users_email;

The statement failed, yet \d shows the index, marked INVALID. It isn't used for reads, it still slows writes, and it must be dropped by hand. Also, CONCURRENTLY can't run inside a transaction block, which matters if your migration tool wraps everything in one.

#Why isn't my index being used?

CauseExampleFix
Most of the table matchesWHERE active = trueIt may be the right plan. Look at the numbers
The table is tinyA few pagesThe right plan again
A function on the columnWHERE lower(email) = 'a'An index on the expression
A leading wildcardLIKE '%abc'A trigram index
Stale statisticsAfter a bulk loadANALYZE
Wrong composite order(a, b) for b, with many a valuesAnother index
A type mismatchComparing text to a numberMatch the types

And the cleanup commands from the course, since they've all appeared here:

CommandWhat it doesCost
VACUUMMarks dead rows reusable, sets the visibility mapLight, runs alongside normal work
ANALYZERefreshes planner statisticsLight
VACUUM (VERBOSE)The same, and reports progressLight
VACUUM FULLRewrites the table to return space to the operating systemExclusive lock, blocks everything

#Things that can trip you up

  • Reading cost as time. It's an arbitrary unit, and only actual time is real.
  • Comparing timings between runs. The first run reads the disk and the second reads the cache. Compare buffers.
  • Believing "Index Only Scan". Check Heap Fetches. If it's large, run VACUUM.
  • Adding an index that doesn't reduce pages read. If matches are spread over every page, you still read every page.
  • EXPLAIN ANALYZE runs the query. On an UPDATE or DELETE, wrap it in a transaction and roll back.
  • Plans differ by version and data. The course says this itself, and this post is the proof: two of its plans changed.
  • CONCURRENTLY waiting forever. One long-running transaction holds up the build.
  • Too many indexes. Check pg_stat_user_indexes for ones that are never scanned.

#Reproduce this yourself

Use the pgacid container from post 1, or any Postgres 18.

  1. ✅ Build the tables. These are the ones I used, at a million rows where the course has 10 to 50 million:
    sql
    CREATE TABLE employees (id serial PRIMARY KEY, name text);
    INSERT INTO employees (name)
    SELECT substr(md5(random()::text), 1, 1 + (random() * 9)::int)
    FROM generate_series(1, 1000000);
    VACUUM ANALYZE employees;
    
  2. ✅ Run each EXPLAIN above. Your timings will differ. Plans should match, apart from small cost differences from random().
  3. ✅ To force a plan for the sweep, turn off the others in your session: SET enable_seqscan = off;. Those settings are for experiments, not production.
  4. ✅ For the skip scan, you need Postgres 18. On 17 the same query should fall back to a sequential scan. 📘 I didn't run 17.
  5. ✅ For the concurrent build, open three psql sessions and follow the replay.

#Glossary

TermMeaning
Planner (optimizer)The part of the database that chooses how to run a query
Startup cost, total costEstimated work before the first row, and for all rows
Index ScanWalks the index and visits the heap for each match
Bitmap Heap ScanNotes the pages first, then reads each one once
Seq ScanReads every page of the table in order
Index Only ScanAnswers from the index, with the visibility map's help
Key column, non-key columnSearchable and sorted, or just carried in the index
Covering indexAn index holding every column a query needs
Composite indexAn index on several columns, sorted left to right
Skip scanUsing a composite index without its leading column, by searching once per leading value
SelectivityThe share of rows a condition matches
StatisticsThe planner's approximate picture of the data, refreshed by ANALYZE
Visibility mapOne bit per heap page: are all its rows visible to everyone?
Heap fetchAn index-only scan having to visit the table after all

#Summary

An index helps by reducing the pages a query reads, and nothing else. The planner estimates that from statistics, and flips between index, bitmap and sequential scans as the share of matching rows grows. Those plans are visible in EXPLAIN, and buffers are a better measure than time. Index-only scans depend on the visibility map, so VACUUM matters. Composite indexes are sorted left to right, and Postgres 18's skip scan softens that rule when the leading column has few values. Every index costs writes, and building one on a live table needs CONCURRENTLY.

#Concepts at a glance

ConceptIn one lineWhy it matters
EXPLAIN ANALYZEThe plan, plus what really happenedThe main tool for query work
CostAn arbitrary unit, startup then totalIt isn't time
BuffersPages touchedThe most honest measure of work
Scan choiceDepends on the share of rows matchingExplains why an index gets ignored
Bitmap AND, ORCombine indexes before touching the tableTwo indexes, one heap trip
Covering indexINCLUDE the columns you selectSkips the table entirely
Visibility mapSet by VACUUM, cleared by writesDecides Heap Fetches
Leftmost prefixComposite indexes sort left to rightColumn order decides what's served
Skip scanPostgres 18 can skip a low-cardinality leading columnThe old rule has an exception
SelectivityDepends on the value, not only the columnSame index, opposite plans
Stale statisticsPlans built on old numbersRun ANALYZE after bulk loads
CONCURRENTLYBuilds without blocking writesHow to index in production

#Test yourself

A plan shows cost=136537.84..139037.84 on a Sort node. What do the two numbers mean, and why is the first so high?

The first is the startup cost, the work before the first row can come out. The second is the total. A sort must read all its input before emitting anything, so nearly all its cost is startup. They're in arbitrary units, not milliseconds.

You add an index on g, and a query with a range on g gets slower. How can that be?

If the matching rows are spread across nearly every page, the query still reads almost the whole table, so the index saves nothing and adds work. In the run above the bitmap scan visited 24,340 pages and also lost parallelism. Fewer pages only came from a covering index, which avoided the table altogether.

EXPLAIN says Index Only Scan, but it's slow, and Heap Fetches is large. What's going on, and what's the fix?

The visibility map bits for those pages aren't set, so each row's visibility had to be checked in the heap. That's common after a bulk load or heavy updates. VACUUM sets the bits.

With a composite index on (a, b), can Postgres serve WHERE b = 40?

On versions before 18 it's generally no, and it falls back to a sequential scan. On 18 a skip scan can use the index if a has few distinct values: it searches once per value of a, and Index Searches shows how many. With many distinct values it still scans the table.

Why doesn't CREATE INDEX CONCURRENTLY block writers, and what can go wrong with it?

It builds from a snapshot, then scans again to catch changes made in the meantime, waiting between phases for older transactions to finish. It's slower, can be held up by one long transaction, can't run inside a transaction block, and if it fails it leaves an INVALID index that you must drop.

#Open questions and gaps

  • The crossover points in the charts are for one table shape, from a warm cache. Cold reads would look different, and I didn't test them.
  • 🎓 The course's timings came from 10 to 50 million rows. I used a million, so absolute numbers aren't comparable. I kept the plans, and said where they differ.
  • The course's a only, LIMIT 2 plan was a plain Index Scan. Mine is a Seq Scan, which finds two matches in the first couple of pages when 1% of rows match. Both avoid building a bitmap, which was the lecture's point.
  • 📘 I didn't test pg_hint_plan, or Oracle or SQL Server hints.
  • 📘 I didn't run Postgres 17 to confirm the skip scan difference. The release notes and the course's output are the evidence.

#Sources