BEGINNERCHAPTER 06

Indexes from the outside: when a query gets fast

Read EXPLAIN (ANALYZE, BUFFERS), add the index that turns 3,600 page reads into 10, and learn the four rules that decide whether the planner will use it

55 MINDATABASESUPDATED 2026-11-02
PREDICT

orders has one index besides the primary key: CREATE INDEX ON orders (customer_id, created_at). You run SELECT * FROM orders WHERE created_at >= '2025-10-01' AND created_at < '2025-10-02' on Postgres 17. About 230 of 200,000 rows match. What plan do you get?

An index is a second copy of some of a table’s columns, sorted, with a pointer from each entry back to its row. In Postgres the default kind is a B+ tree: a few levels of internal pages that route a search, and a bottom level of leaf pages holding the sorted entries, linked left to right. A search for one key reads one page per level, three or four pages for a table of millions of rows. A range search finds the first key the same way and then reads leaf pages sideways until it passes the last one.

That is the whole mechanism, and the B+ trees in the engine chapter in module D2 opens it up. This chapter stays outside. You will learn to read the plan Postgres prints, to predict whether an index will be used before you create it, and to count what each index costs. All of it on the shop.

Reading EXPLAIN (ANALYZE, BUFFERS)

EXPLAIN prints the plan the planner chose and its estimates. EXPLAIN (ANALYZE) runs the query and adds what happened. BUFFERS adds how many 8 kB pages each step touched. Use all three, every time; the timings mislead you about caching and the buffer counts do not.

Here is the support-tool query on the shop at scale 0.1 (200,000 orders), before any index on customer_id:

Seq Scan on orders  (cost=0.00..4339.00 rows=6 width=43) (actual time=1.459..5.184 rows=4 loops=1)
  Filter: (customer_id = 4242)
  Rows Removed by Filter: 199996
  Buffers: shared hit=1839
Execution Time: 5.186 ms

Read it bottom up, because rows flow upward; here there is only one node. Seq Scan means one process reads the table from start to end and keeps rows that pass the Filter. Rows Removed by Filter: 199996 means 200,000 rows were read to find 4. Buffers: shared hit=1839 means 1,839 pages, 14 MB, all of the table. At scale 1 the table is big enough for the planner to split the scan: you see a Gather over a Parallel Seq Scan with loops=3 (two workers plus the leader, each reading a third of the table, so Rows Removed by Filter is per process). hit means the page was in Postgres’s shared buffer cache; read would mean it came from the operating system, which may or may not have had it in its own cache. cost= is the planner’s estimate in arbitrary units (one sequential page read is 1.0); actual time= is milliseconds, first row..last row. Compare estimated rows=6 with actual rows=4: when these differ by orders of magnitude, the planner chose with bad information, and the planner chapter in D2 is about why.

After CREATE INDEX orders_customer_id ON orders (customer_id);:

Bitmap Heap Scan on orders  (cost=4.47..27.51 rows=6 width=43) (actual time=0.017..0.018 rows=4 loops=1)
  Recheck Cond: (customer_id = 4242)
  Heap Blocks: exact=4
  Buffers: shared hit=7 read=3
  ->  Bitmap Index Scan on orders_customer_id  (cost=0.00..4.46 rows=6 width=0) (actual time=0.014..0.014 rows=4 loops=1)
        Index Cond: (customer_id = 4242)
        Buffers: shared hit=3 read=3
Execution Time: 0.024 ms

Index Cond is the condition the index searched by; contrast it with Filter, which is a condition checked on rows after they were fetched. The index scan touched 6 pages and the heap scan 4 more: 10 pages instead of 1,839, and 0.024 ms instead of 5. At scale 1 the sequential scan grows tenfold and the index scan does not grow at all, because the tree is the same depth.

There are three ways to use an index, and EXPLAIN names them:

Node What it does When the planner picks it
Index Scan walk the index in order, fetch each row from the heap as you go few rows, or the query needs the index’s order (ORDER BY, LIMIT)
Bitmap Index Scan + Bitmap Heap Scan collect matching row locations from the index, sort them by page, then read each heap page once a few hundred to a few thousand rows spread over many pages
Index Only Scan answer from the index alone, visiting the heap only for pages not marked all-visible every column the query uses is in the index

EXPLAIN ANALYZE executes the statement. For an UPDATE or DELETE, wrap it: BEGIN; EXPLAIN (ANALYZE, BUFFERS) DELETE ...; ROLLBACK;.

Composite indexes and the leftmost-prefix rule

A composite index on (customer_id, created_at) is sorted by customer_id, and by created_at only among entries with the same customer_id. Think of a phone book sorted by surname, then first name:

customer_id created_at row
4241 2025-11-30 (1201, 7)
4242 2024-06-02 (88, 14)
4242 2024-12-19 (530, 2)
4242 2025-03-07 (1702, 33)
4243 2024-01-15 (9, 41)

That ordering decides which conditions the index can search by:

  • customer_id = 4242: one contiguous run of entries. Searchable.
  • customer_id = 4242 AND created_at >= '2025-01-01': a contiguous sub-run inside that run. Searchable, and both columns appear in Index Cond.
  • created_at >= '2025-10-01' alone: matching entries are scattered through every customer’s run. Not searchable. The planner can still read the whole index and filter it, but that rarely beats reading the table.
  • customer_id > 4000 AND created_at = '2025-03-07': the range on the first column is searched; the condition on the second is checked on every entry in that range without narrowing it.

So the rule: an index can be searched by a leftmost prefix of its columns, with equality on every column except possibly the last one used, which can be a range. Put the columns you filter by equality first, the column you range over or sort by last. (customer_id, created_at) serves “this customer’s orders, newest first” with no sort step: ORDER BY created_at DESC LIMIT 20 reads the run backwards and stops after 20 entries.

The rule also means one composite index often replaces two. (customer_id, created_at) serves every query that (customer_id) alone would, so keeping both costs writes for nothing. The reverse is not true: (created_at, customer_id) serves neither the customer lookup nor this ordering.

Postgres 18 adds skip scan for B-trees: with a condition only on later columns, it can jump from one leading value to the next and search within each. It pays when the leading column has few distinct values (a region with 5 values), not when it has 50,000. This course uses Postgres 17, where the rule above is exact.

Covering indexes and index-only scans

Every match in an ordinary index scan costs a heap visit to fetch the rest of the row, and on a table bigger than memory that is a random read per row. If the index already contains every column the query needs, Postgres can skip the heap.

-- index on (customer_id, created_at)
SELECT customer_id, created_at FROM orders WHERE customer_id = 4242;
--   Index Only Scan ... Heap Fetches: 0 ... Buffers: shared hit=4
SELECT customer_id, created_at, total_cents FROM orders WHERE customer_id = 4242;
--   Bitmap Heap Scan ... Buffers: shared hit=7

Asking for one more column sends the query back to the heap. To cover it without making total_cents part of the sort key, use INCLUDE:

CREATE INDEX orders_customer_created_inc
  ON orders (customer_id, created_at) INCLUDE (status, total_cents);

INCLUDE columns sit only in the leaf entries. They are not searchable and do not affect order; they are payload. They make the index bigger, 9.7 MB against 6.2 MB for the same keys without them at scale 0.1, and every update of status now has to update this index too.

There is a catch particular to Postgres. An index entry does not say whether its row is visible to your transaction; that information lives in the heap. Postgres keeps a visibility map, one bit per heap page meaning “every row here is visible to everyone”. For pages with the bit set, the index-only scan trusts the index. For the rest it visits the heap anyway, and EXPLAIN counts those visits as Heap Fetches. VACUUM sets the bits; any write to a page clears it. On a freshly bulk-loaded table, before autovacuum has run, an “index-only” scan can fetch every row from the heap. If Heap Fetches is high, run VACUUM orders; and look again.

Why the planner ignores your index

You create an index on orders.status and the planner does not use it for WHERE status = 'shipped'. That is the planner being right. 85% of orders are shipped. Fetching 170,000 rows through the index means visiting nearly every heap page anyway, in index order, which is random order. A sequential scan reads the same pages once, in order, and the disk and the operating system’s read-ahead are built for that.

The planner decides with statistics and a cost model. ANALYZE (run by autovacuum) samples each column and stores the most common values and their frequencies in pg_stats; for status it records {shipped, cancelled, paid, placed} with frequencies around {0.85, 0.07, 0.05, 0.03}. The cost model charges seq_page_cost = 1 for a page read in sequence and random_page_cost = 4 for a page read at random. Multiply out and the crossover for a typical table falls somewhere between 5% and 20% of rows: below it the index wins, above it the scan does.

So the same index is used or ignored depending on the value. WHERE status = 'placed' (3%) uses it as a bitmap scan. WHERE status = 'shipped' (85%) does not. An index on a two-valued boolean is almost never useful, unless the value you look for is the rare one, which is what partial indexes are for. The index selectivity lesson plays out the crossover step by step.

Three other reasons an index is not used, all common:

  • A function on the column. WHERE lower(email) = 'a@b.com' cannot use an index on email. Create an expression index, CREATE INDEX ON customers (lower(email)), or store the value normalised.
  • A type mismatch. Comparing a bigint column with a numeric parameter casts the column, and the index on it is no longer usable. ORMs do this more than you think.
  • Stale statistics. After a bulk load, until ANALYZE runs, the planner may think the table is empty. Run ANALYZE after loading.

random_page_cost = 4 dates from spinning disks. On SSDs many teams set it to 1.1, which moves the crossover toward the index. Change it only after you have measured; it affects every query.

What every index costs

An index makes some reads faster and every write slower. Each INSERT into a table with eight indexes does nine B-tree descents and page modifications (the heap plus eight), writes WAL for each, and dirties pages that checkpoints must flush later. Each DELETE leaves dead entries in every index for vacuum to clean.

In the lab you measure it with a scratch copy of orders and pgbench inserting one row per transaction from 4 clients:

Extra indexes Inserts per second Average latency
0 16,200 0.25 ms
3 14,900 0.27 ms
8 13,700 0.29 ms

A 16% drop looks modest, because most of each single-row transaction’s time is the commit itself, the WAL flush from the previous chapter. The size tells the louder story: after about 450,000 inserted rows the table was 47 MB and its indexes 129 MB. Indexes compete with the table for the same shared buffers and page cache, so every index you add pushes out pages that queries need. Batch inserts with COPY, where the commit cost is spread across thousands of rows, and the index share of the cost grows much larger.

Updates have a subtler cost. Postgres can do a HOT update (heap-only tuple) when the update changes no indexed column and the new row version fits on the same page: no index is touched at all. Index a column that changes on every update, such as inventory.updated_at, and every stock change must now write a new entry into every index on inventory. pg_stat_user_tables.n_tup_hot_upd against n_tup_upd tells you how often you are getting HOT updates.

So before creating an index, name the query it serves. After creating it, check that it is used: pg_stat_user_indexes.idx_scan counts scans per index since the statistics were last reset. An index with idx_scan = 0 after a month of production traffic is pure cost.

Partial indexes

Most operational queries look at a small, fixed slice of a table: open orders, failed payments, unshipped items. A partial index indexes only that slice.

CREATE INDEX orders_open ON orders (created_at)
  WHERE status IN ('placed', 'paid');

About 8% of orders are placed or paid, so this index is about a tenth the size of a full index on created_at: 368 kB at scale 0.1 against 4.4 MB. It is never touched by inserts or updates of shipped orders, and it answers “orders still open after 7 days” directly.

The planner uses it only when it can prove that the query’s WHERE implies the index’s predicate. WHERE status = 'placed' AND created_at < now() - interval '7 days' qualifies: status = 'placed' implies status IN ('placed', 'paid'). WHERE status = $1 in a prepared statement does not, because the match happens at planning time and $1 could be anything. Postgres does not prove equivalences in general; write the query’s condition in the same form as the index’s.

Partial unique indexes are a correctness tool too. CREATE UNIQUE INDEX ON payments (order_id) WHERE status = 'captured'; makes it impossible to capture two payments for one order, while allowing any number of failed attempts.

What a B+ tree does under the hood

Before the lab, step through the tree itself. In LOOKUP + RANGE SCAN, watch the lookup for 42 read one node per level, root to leaf, and then the range scan for 42..50 move sideways along the leaf links without going back up: that sideways walk is why a composite index serves customer_id = 4242 AND created_at >= ... as one contiguous read. In B+ TREE: SORTED INSERTS, watch every new key land in the rightmost leaf and split it, and the tree grow at the root so that every leaf stays at the same depth. Then compare NO SPLITS: BINARY TREE, where the same sorted keys build a chain one node per key: the reason databases use wide, balanced trees.

▶ SIMULATION
B+ TREE · FANOUT 4
keys 0 · max keys/node 3
leaf splits 0 · internal 0 · root 0
—
NODES BY LEVEL
leaves (depth 1): []
QUERY
leaf depth 1
lookup: —
leaf chain— (1 leaves)
✓ all leaves at the same depth✓ keys in order across leaves, none lost
SCHEDULE
01[LOAD]insert 16 keys, 5 … 60
02[QUERY]lookup 42: descend from the root to a leaf
03[QUERY]range scan 42..50: follow leaf next pointers
04[QUERY]report
Start of lookup + range scan scenario. 4 steps.
B+ tree (fanout F: at most F children, F-1 keys per node)
===================================================

Structure
  internal nodes: keys + child pointers only (no row data)
  leaves: keys + row data (or row ids), linked by next pointers
  every leaf sits at the same depth

Lookup(K)
  start at root; pick the child whose range holds K; repeat to a leaf
  cost: one page read per level = height

Range(lo, hi)
  lookup(lo), then follow leaf next pointers until a key > hi

Insert(K)
  1. find the leaf, insert K in sorted position
  2. leaf overfull? split into left | right,
     COPY right[0] up to the parent as the separator
  3. parent overfull? split it, MOVE its middle key up
  4. root split? make a new root: the tree grows by one level,
     at the top, so all leaves stay at the same depth

Why it stays shallow
  fanout 500, 3 levels  -> ~125 million keys, 3 page reads
  balanced binary tree  -> ~27 levels for the same keys
  unbalanced binary tree, sorted inserts -> one level per key
BREAK IT NOT YET

The same seven sorted inserts run at every fanout. At FANOUT 4 the root splits once and the tree stops at 2 levels. Change FANOUT until the root has to split a second time and the tree grows to 3 levels.

GOAL: the seven inserts grow the tree to 3 levels

LAB Make a query fast, then count the bill ~40 MIN
YOU NEEDDocker Desktop or Docker Engine with Composelabs/databases started with `docker compose up -d` and loaded at scale 0.1 (`docker compose exec -T db psql -U atlas -d shop -v scale=0.1 -f /shop/load.sql`); at scale 1 multiply page counts by tenpsql via `docker compose exec db psql -U atlas shop`

Your numbers will differ from the ones below in detail; the ratios and the plan shapes are what to check. Work in psql in labs/databases.

1. Start from a clean table and a baseline.

\timing on
\d orders
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap,
       pg_size_pretty(pg_indexes_size('orders')) AS indexes;
VACUUM ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 4242;
\d orders lists only orders_pkey under Indexes (drop any index an earlier chapter left, with DROP INDEX name;). The heap is 14 MB at scale 0.1 (144 MB at scale 1). The plan is a Seq Scan with Rows Removed by Filter: 199996 and Buffers: shared hit=1839, the entire table, to return 4 rows in about 5 ms. At scale 1 it is a Gather over a Parallel Seq Scan reading 18,382 buffers to return 2 rows.

2. Add the index and measure again.

CREATE INDEX orders_customer_id ON orders (customer_id);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 4242;
SELECT pg_size_pretty(pg_relation_size('orders_customer_id'));
Bitmap Index Scan on orders_customer_id under a Bitmap Heap Scan, about 10 buffers in total, and an execution time well under 1 ms: a reduction in pages of about 180 times at scale 0.1 and about 2,000 at scale 1. The index is about 2.4 MB, smaller than the 4.4 MB primary key, because Postgres 13 and later deduplicate repeated keys in B-tree leaves.

3. Composite index and the leftmost-prefix rule.

DROP INDEX orders_customer_id;
CREATE INDEX orders_customer_created ON orders (customer_id, created_at);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders
  WHERE customer_id = 4242 AND created_at >= '2025-01-01';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders
  WHERE created_at >= '2025-10-01' AND created_at < '2025-10-02';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders
  WHERE customer_id = 4242 ORDER BY created_at DESC LIMIT 3;
The first uses orders_customer_created with both columns in Index Cond. The second, on created_at alone, is back to a sequential scan (a Parallel Seq Scan under Gather) over all 1,839 pages: the Predict, confirmed. The third is an Index Scan Backward with no Sort node: the index already holds this customer’s orders in date order, so Postgres reads three entries from the end and stops.

4. Covering index and Heap Fetches.

EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id, created_at FROM orders WHERE customer_id = 4242;
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id, created_at, total_cents FROM orders WHERE customer_id = 4242;
CREATE INDEX orders_customer_created_inc ON orders (customer_id, created_at) INCLUDE (status, total_cents);
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS) SELECT customer_id, created_at, total_cents FROM orders WHERE customer_id = 4242;
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) FROM pg_stat_user_indexes WHERE relname = 'orders';
The first is an Index Only Scan with Heap Fetches: 0 and about 4 buffers. Adding total_cents makes it a Bitmap Heap Scan again, about 7 buffers. After the INCLUDE index, the same query is an Index Only Scan using orders_customer_created_inc. The size listing shows the price: about 9.7 MB for the INCLUDE index against 6.2 MB for the same keys without it. Now UPDATE orders SET status = 'paid' WHERE customer_id = 4242; and rerun the last EXPLAIN: Heap Fetches is no longer 0, because the update cleared the visibility bits on those pages. VACUUM orders; sets them back.

5. An index the planner ignores, and one it uses for some values.

DROP INDEX orders_customer_created_inc;
SELECT most_common_vals, most_common_freqs FROM pg_stats
  WHERE tablename = 'orders' AND attname = 'status';
CREATE INDEX orders_status ON orders (status);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE status = 'shipped';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE status = 'placed' AND created_at < '2024-01-01';
shipped is about 0.85 of rows. The shipped query is a sequential scan despite the index. The placed query, about 3% of rows, uses Bitmap Index Scan on orders_status and then filters created_at on the heap: Rows Removed by Filter is in the thousands, every one of them a row fetched for nothing. One twist to try: EXPLAIN SELECT count(*) FROM orders WHERE status = 'shipped'; may use an Index Only Scan, because a count needs no columns and the index is far smaller than the table.

6. A partial index for open orders.

DROP INDEX orders_status;
CREATE INDEX orders_open ON orders (created_at) WHERE status IN ('placed', 'paid');
SELECT pg_size_pretty(pg_relation_size('orders_open'));
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE status = 'placed' AND created_at < '2024-01-01';
PREPARE open_q(text) AS SELECT * FROM orders WHERE status = $1 AND created_at < '2024-01-01';
SET plan_cache_mode = force_generic_plan;
EXPLAIN EXECUTE open_q('placed');
RESET plan_cache_mode;
The partial index is about 370 kB, roughly a tenth of a full index on created_at. The query uses Index Scan using orders_open with created_at in Index Cond and status = 'placed' as a Filter, and reads about 17 buffers against roughly 1,770 for the orders_status plan in step 5. The prepared statement with a generic plan cannot use it, because status = $1 does not imply status IN ('placed', 'paid') for every $1; you see a scan that does not mention orders_open. Leave orders_customer_created and orders_open in place: the D1 project lists the indexes earlier chapters left and drops them before it measures.

7. Count the write cost: 0, 3 and 8 indexes.

Create a scratch table shaped like orders and a pgbench script that inserts one row per transaction:

docker compose exec db psql -U atlas shop -c "CREATE TABLE bench_orders (id bigserial PRIMARY KEY, customer_id bigint NOT NULL, status text NOT NULL, total_cents int NOT NULL, created_at timestamptz NOT NULL, shipped_at timestamptz, note text);"
docker compose exec -T db sh -c 'cat > /tmp/ins.sql' <<'EOF'
\set cid random(1, 50000)
\set total random(100, 100000)
INSERT INTO bench_orders (customer_id, status, total_cents, created_at, shipped_at, note)
VALUES (:cid, 'placed', :total, now() - (random() * interval '1000 days'), NULL, md5(random()::text));
EOF
docker compose exec db pgbench -U atlas -n -c 4 -T 10 -f /tmp/ins.sql shop | grep -E "^tps|latency average"

Add three indexes and run it again, then five more and run it a third time:

docker compose exec db psql -U atlas shop -c "CREATE INDEX b1 ON bench_orders (customer_id); CREATE INDEX b2 ON bench_orders (created_at); CREATE INDEX b3 ON bench_orders (status, created_at);"
docker compose exec db pgbench -U atlas -n -c 4 -T 10 -f /tmp/ins.sql shop | grep -E "^tps|latency average"
docker compose exec db psql -U atlas shop -c "CREATE INDEX b4 ON bench_orders (total_cents); CREATE INDEX b5 ON bench_orders (note); CREATE INDEX b6 ON bench_orders (customer_id, created_at) INCLUDE (total_cents); CREATE INDEX b7 ON bench_orders (shipped_at); CREATE INDEX b8 ON bench_orders (status, total_cents);"
docker compose exec db pgbench -U atlas -n -c 4 -T 10 -f /tmp/ins.sql shop | grep -E "^tps|latency average"
docker compose exec db psql -U atlas shop -c "SELECT count(*), pg_size_pretty(pg_relation_size('bench_orders')) AS heap, pg_size_pretty(pg_indexes_size('bench_orders')) AS indexes FROM bench_orders;"
Something like 16,000, 15,000 and 13,700 tps, with average latency rising from about 0.25 ms to 0.29 ms. The final query shows the indexes several times the size of the table: 129 MB against 47 MB in the reference run. The note index on random md5 text is the largest and serves no query at all. Drop the table when you are done: DROP TABLE bench_orders;.
Take an index away from a foreign key and delete one parent row. order_items.order_id references orders(id), and nothing indexes it. Create an order with no items and delete it inside a transaction you roll back: BEGIN; INSERT INTO orders (customer_id, status, total_cents, created_at) VALUES (1, 'placed', 0, now()) RETURNING id \gset then EXPLAIN (ANALYZE, BUFFERS) DELETE FROM orders WHERE id = :id; then ROLLBACK;. The DELETE itself is cheap, but the output ends with Trigger for constraint order_items_order_id_fkey and Trigger for constraint payments_order_id_fkey lines whose times are many milliseconds: to check that nothing still points at the order, Postgres scanned all of order_items and all of payments. Deleting a thousand orders this way reads the table a thousand times. Now CREATE INDEX order_items_order_id ON order_items (order_id); and repeat: the order_items trigger time drops to a fraction of a millisecond (payments needs the same treatment). That index is also what every ‘items of this order’ join needs, which makes it the first entry in the project’s index file.
DECIDE

The support tool runs SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 about 50 times a minute. orders has 20 million rows and takes 300 inserts per second from checkout plus an update of status for each shipment. EXPLAIN shows a Parallel Seq Scan and a Sort, 1.4 seconds per call. Only the primary key exists. Which index do you create?

READING
  1. BOOK
    Use The Index, Luke: The Where Clause Markus Winand

    The free web edition of SQL Performance Explained. The clearest explanation anywhere of why column order matters, with Postgres examples. Skip the Oracle-specific NULL section. Read: the Equals Operator and Concatenated Keys sections, then Searching for Ranges and Partial Indexes.

  2. BOOK
    Use The Index, Luke: Clustering Data and Index-Only Scans Markus Winand

    Why heap fetches dominate the cost of an index scan, and when covering an index is worth its size. Pairs with step 4 of the lab. Read: Index-Only Scan and the Clustering Factor sections.

  3. DOC
    Use The Index, Luke: Getting an Execution Plan in PostgreSQL Markus Winand

    A short guide to EXPLAIN in Postgres and the names of its operations. Read it once and keep the operations page open while reading plans.

  4. DOC
    PostgreSQL 17 documentation: Multicolumn Indexes

    The official statement of the leftmost-prefix behaviour, including the exact wording on conditions for non-leading columns. Two paragraphs; read all of it.

  5. DOC
    PostgreSQL 17 documentation: Index-Only Scans and Covering Indexes

    The visibility-map caveat, the INCLUDE clause and its restrictions, and when covering does not pay. The source for every claim in the covering-index section.

  6. DOC
    PostgreSQL 17 documentation: Partial Indexes

    Examples of partial indexes for excluding common values and for partial uniqueness, and the precise rule for when the planner can match one.

  7. DOC
    PostgreSQL 17 documentation: Using EXPLAIN

    How costs are computed, what each EXPLAIN ANALYZE field means, and the caveats about timing overhead. Read 14.1.1 and 14.1.2; the estimate details belong to the planner chapter.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: build and query the shop database →