Read EXPLAIN like a pro: selectivity and correlation, composite index column order, the ORDER BY LIMIT trap, covering and partial indexes, write costs and planner misestimates, all measured on 2 million rows in PostgreSQL 16.
Most slow queries are missing an index, using the wrong one, or written in a way that stops the database from using the right one. A few are slow because the planner guessed wrong. You can tell these apart in a minute if you can read a query plan, and that's what this article teaches.
Everything below ran on PostgreSQL 16 against a table of 2 million orders (208 MB) and 100,000 customers. Every plan is real EXPLAIN (ANALYZE, BUFFERS) output. The ideas carry over to MySQL, SQL Server and others: B-trees, selectivity and column order work the same everywhere.
It builds on How a Database Works Inside, which covered pages, the buffer pool and how a B-tree is laid out on disk.
CREATE TABLE customers (
id int PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
city text NOT NULL
);
-- 100k customers; city determines country (correlated columns)
INSERT INTO customers
SELECT i,
'User' || i || '@Example.com',
(ARRAY['NP','NP','IN','US','GB','DE'])[1 + (i % 6)],
(ARRAY['Kathmandu','Pokhara','Delhi','Austin','London','Berlin'])[1 + (i % 6)]
FROM generate_series(1, 100000) i;
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id int NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total numeric(10,2) NOT NULL,
note text
);
-- 2M orders over two years, inserted in time order; status heavily skewed
INSERT INTO orders (customer_id, status, created_at, total, note)
SELECT 1 + (random() * 99999)::int,
CASE WHEN r < 0.90 THEN 'delivered' WHEN r < 0.95 THEN 'shipped' WHEN r < 0.99 THEN 'pending'
WHEN r < 0.999 THEN 'cancelled' ELSE 'refunded' END,
timestamptz '2025-01-01' + (i * interval '31.536 seconds'),
round((random() * 500)::numeric, 2),
repeat('x', 40)
FROM (SELECT i, random() AS r FROM generate_series(1, 2000000) i) s;
VACUUM ANALYZE customers;
VACUUM ANALYZE orders;
Two properties of this data matter later. Orders were inserted in time order, so created_at follows the table's physical order, while customer_id is random. And status is heavily skewed: 90% delivered, 0.1% refunded. Real data is like this.
A B-tree index is a sorted copy of one or more columns, each entry pointing to a row's location in the table (in PostgreSQL, a page number and slot, called a TID). The sorted entries are grouped into 8 KB leaf pages, with a few levels of internal pages on top so the database can find any key in a handful of page reads.
That gives you two operations:
Everything about indexing follows from this picture. An index helps when the rows you want are a contiguous slice of that sorted list, and the slice is small, or already in the order you need.
Find one customer's orders without an index:
Gather (cost=1000.00..38085.77 rows=21 width=76) (actual time=0.894..52.570 rows=19 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=13791 read=12876
-> Parallel Seq Scan on orders (cost=0.00..37083.67 rows=9 width=76) (actual time=1.527..47.687 rows=6 loops=3)
Filter: (customer_id = 4242)
Rows Removed by Filter: 666660
Buffers: shared hit=13791 read=12876
Planning:
Buffers: shared hit=70 read=2
Planning Time: 0.215 ms
Execution Time: 52.647 ms
Three processes read all 26,667 pages of the table and threw away 2 million rows to find 19. Now CREATE INDEX orders_customer_idx ON orders (customer_id) and run it twice:
Bitmap Heap Scan on orders (cost=4.59..87.08 rows=21 width=76) (actual time=0.006..0.012 rows=19 loops=1)
Recheck Cond: (customer_id = 4242)
Heap Blocks: exact=19
Buffers: shared hit=22
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.58 rows=21 width=0) (actual time=0.004..0.004 rows=19 loops=1)
Index Cond: (customer_id = 4242)
Buffers: shared hit=3
Planning Time: 0.020 ms
Execution Time: 0.018 ms
22 pages instead of 26,667: 3 index pages (root, one internal page, one leaf) plus 19 table pages, one per matching row, because this customer's orders are scattered through the table. The first run, with a cold cache, took 0.12 ms; this one 0.018 ms. Either way, about 3,000 times faster than the scan.
A plan is a tree. Each node pulls rows from its children; read it from the most indented line outwards. On every node:
| Part | Meaning |
|---|---|
cost=4.59..87.08 |
The planner's estimate, in arbitrary units: cost to return the first row, and all rows. Only useful for comparing plans for the same query. |
rows=21 (in the cost part) |
How many rows the planner expected. |
actual time=0.006..0.012 |
Real milliseconds to first row and to last row, per loop. |
rows=19 (in the actual part) |
How many rows really came out, per loop. |
loops=1 |
How many times this node ran. Multiply time and rows by this. |
Buffers: shared hit=22 read=0 |
Pages found in PostgreSQL's cache (hit) or fetched from the OS (read). The best measure of work done. |
Rows Removed by Filter |
Rows read and thrown away: wasted work. |
Two habits catch most problems:
Always use EXPLAIN (ANALYZE, BUFFERS). Plain EXPLAIN shows only estimates. Remember that ANALYZE really runs the query, so wrap data-changing statements in BEGIN; ... ROLLBACK;.
An index is fast for a few rows. But each row found through the index may need a separate table page, possibly a random read. Past some fraction of the table, reading the whole table sequentially is cheaper. Where's the crossover?
Here are three ways to run SELECT sum(total) FROM orders WHERE <condition>, each forced in turn, single-process, best of three runs, for two columns:
created_at: fraction of rows | seq scan | index scan | bitmap scan | planner picks
0.01% | 101.8 ms | 0.2 ms | 0.2 ms | Index Scan
0.10% | 101.9 ms | 0.4 ms | 0.4 ms | Index Scan
1.00% | 102.1 ms | 2.3 ms | 2.3 ms | Index Scan
5.00% | 106.9 ms | 12.3 ms | 13.0 ms | Index Scan
10.00% | 112.0 ms | 23.7 ms | 24.6 ms | Index Scan
25.00% | 118.7 ms | 54.0 ms | 56.5 ms | Index Scan
50.00% | 142.5 ms | 108.1 ms | 113.6 ms | Index Scan
customer_id: fraction of rows | seq scan | index scan | bitmap scan | planner picks
0.01% | 88.2 ms | 0.2 ms | 0.2 ms | Bitmap
0.10% | 88.8 ms | 0.5 ms | 1.1 ms | Bitmap
1.00% | 89.9 ms | 7.0 ms | 11.9 ms | Bitmap
5.00% | 94.5 ms | 108.2 ms | 82.7 ms | Bitmap
10.00% | 109.5 ms | 275.2 ms | 98.9 ms | Bitmap
25.00% | 129.6 ms | 695.1 ms | 142.8 ms | Bitmap
50.00% | 148.4 ms | 1277.4 ms | 204.1 ms | Bitmap
The difference is correlation: how closely the index order matches the physical order of rows in the table. PostgreSQL tracks it per column:
physical-order correlation: {'customer_id': Decimal('0.000'), 'created_at': Decimal('1.000')}
created_at (correlation 1.0), consecutive index entries point to consecutive rows on the same table pages. An index scan reads each page once, in order. It beats the full scan even at 50% of the table.customer_id (correlation 0), consecutive index entries point all over the table. A plain index scan visits pages at random and revisits them many times: by 5% it's slower than reading everything, and at 50% it's 8.6× slower.Note the last two lines of the second table: the planner chose a bitmap scan at 25% and 50% where a sequential scan was faster. Its estimated costs were nearly a tie (53,467 for bitmap against 54,181 for the seq scan). The cost model's default random_page_cost = 4 says random reads cost four times a sequential read, which was true of spinning disks; here everything is in memory. More on that below.
The rule of thumb: an index on an uncorrelated column helps for up to a few percent of the rows. On a correlated column (an append-only timestamp, an auto-increment id) it helps much further.
A composite index on (customer_id, created_at) sorts by customer first, then by date within each customer: like a phone book sorted by surname, then first name. That ordering decides which queries it serves.
Pick an index and a query. Each line is one index entry, in index order; colour shows what the database reads:
Things to try:
(customer, date) with customer = 'chen' ORDER BY date DESC LIMIT 3: three entries read, no sort. The index is a perfect fit.date >= '2026-10-01': the dates for each customer are sorted, but the matches are scattered across every customer's section. No usable prefix.(date, customer) with customer = 'chen' AND date >= ...: it can only use the range on date, then must check customer on every entry in that range.(status, date) with status = 'pending' ORDER BY date LIMIT 3: equality on the first column, sort on the second, so no sort is needed.The rules that fall out:
(a, b, c) serves conditions on a, on a, b, or on a, b, c, but not on b alone.Rule 1, measured: counting orders since a date with only (customer_id, created_at) available, compared with a dedicated (created_at) index:
Aggregate (cost=45846.73..45846.74 rows=1 width=8) (actual time=35.542..35.543 rows=1 loops=1)
Buffers: shared hit=3 read=7663 written=1646
-> Index Only Scan using orders_cust_created_idx on orders (cost=0.43..45839.87 rows=2744 width=0) (actual time=1.000..35.335 rows=2740 loops=1)
Index Cond: (created_at >= '2026-12-31 00:00:00+01'::timestamp with time zone)
Heap Fetches: 0
Buffers: shared hit=3 read=7663 written=1646
Aggregate (cost=88.33..88.34 rows=1 width=8) (actual time=0.297..0.297 rows=1 loops=1)
Buffers: shared hit=4 read=8
-> Index Only Scan using orders_created_idx on orders (cost=0.43..81.34 rows=2795 width=0) (actual time=0.007..0.198 rows=2740 loops=1)
Index Cond: (created_at >= '2026-12-31 00:00:00+01'::timestamp with time zone)
Heap Fetches: 0
Buffers: shared hit=4 read=8
The first plan says Index Cond, which looks fine, but it read 7,666 pages, the whole index, because the matching dates are spread across 100,000 customer sections. The right index read 12. Read the buffers, not the node name.
(PostgreSQL 18 added a "skip scan" that can jump between the values of a leading column when it has only a few distinct values. With 100,000 customers it wouldn't help here.)
"Show this customer's 10 most recent orders" is one of the most common queries in any application. With separate indexes on customer_id and created_at, the planner has an appealing option: walk the created_at index backwards from the newest order, check each row's customer, and stop at 10. If the customer's orders are spread evenly through time, it finds 10 quickly.
Customer 8 is different: 42,484 orders, almost all from January 2025. The planner's statistics don't know that:
Limit (cost=0.43..24.24 rows=10 width=22) (actual time=8.200..123.388 rows=10 loops=1)
Buffers: shared hit=64572 read=11178 written=8924
-> Index Scan Backward using orders_created_idx on orders (cost=0.43..96694.51 rows=40600 width=22) (actual time=8.200..123.381 rows=10 loops=1)
Filter: (customer_id = 8)
Rows Removed by Filter: 1128323
Buffers: shared hit=64572 read=11178 written=8924
Execution Time: 123.407 ms
It walked backwards through 1.1 million rows before finding 10 for customer 8. The planner assumed the customer's 40,600 orders were spread evenly, so it expected to stop after about 500. With a composite index on (customer_id, created_at):
Limit (cost=0.43..23.66 rows=10 width=22) (actual time=0.023..0.039 rows=10 loops=1)
Buffers: shared hit=10 read=3
-> Index Scan Backward using orders_cust_created_idx on orders (cost=0.43..94320.85 rows=40600 width=22) (actual time=0.022..0.037 rows=10 loops=1)
Index Cond: (customer_id = 8)
Buffers: shared hit=10 read=3
Execution Time: 0.051 ms
13 pages, 0.05 ms, 2,400 times faster, and stable no matter how the customer's orders are distributed. This is the textbook case for a composite index: equality on the first column, ORDER BY on the second, a LIMIT. Every "latest N items for this user" query in an application wants one.
If every column a query needs is in the index, the database can answer from the index alone and skip the table: an index-only scan. INCLUDE adds extra columns to the leaf entries without making them part of the sort key:
CREATE INDEX orders_cust_created_incl_idx ON orders (customer_id, created_at) INCLUDE (total);
Summing a heavy customer's 25,013 orders for 2026, before and after:
Aggregate (cost=28871.82..28871.83 rows=1 width=32) (actual time=5.094..5.095 rows=1 loops=1)
Buffers: shared hit=443 read=4
-> Bitmap Heap Scan on orders (cost=638.29..28809.90 rows=24767 width=6) (actual time=1.117..3.317 rows=25013 loops=1)
Recheck Cond: ((customer_id = 7) AND (created_at >= '2026-01-01 00:00:00+00'::timestamp with time zone))
Heap Blocks: exact=349
-> Bitmap Index Scan on orders_cust_created_idx (cost=0.00..632.10 rows=24767 width=0) (actual time=1.078..1.078 rows=25013 loops=1)
Index Cond: ((customer_id = 7) AND (created_at >= '2026-01-01 00:00:00+00'::timestamp with time zone))
Buffers: shared hit=98
Aggregate (cost=1049.69..1049.70 rows=1 width=32) (actual time=3.710..3.711 rows=1 loops=1)
Buffers: shared hit=1 read=126
-> Index Only Scan using orders_cust_created_incl_idx on orders (cost=0.43..987.77 rows=24767 width=6) (actual time=0.019..2.137 rows=25013 loops=1)
Index Cond: ((customer_id = 7) AND (created_at >= '2026-01-01 00:00:00+00'::timestamp with time zone))
Heap Fetches: 0
Buffers: shared hit=1 read=126
447 pages down to 127, and no table pages at all (Heap Fetches: 0).
There's a catch specific to PostgreSQL. Because of MVCC (#0028), an index entry doesn't say whether its row version is visible to your transaction. PostgreSQL can skip the table only for pages marked "all visible" in the visibility map, which VACUUM maintains. Update some of those rows and run it again:
Aggregate (cost=1057.69..1057.70 rows=1 width=32) (actual time=9.698..9.699 rows=1 loops=1)
-> Index Only Scan using orders_cust_created_incl_idx on orders (cost=0.43..995.77 rows=24767 width=6) (actual time=0.024..7.716 rows=25013 loops=1)
Index Cond: ((customer_id = 7) AND (created_at >= '2026-01-01 00:00:00+00'::timestamp with time zone))
Heap Fetches: 29402
Buffers: shared hit=29540
29,402 heap fetches, more than the number of rows returned, because the index now also holds entries for the old row versions. After VACUUM, it's back to 102 heap fetches and 272 buffers. On a busy table, index-only scans are only as good as your autovacuum settings.
An index on email stores emails as written. A case-insensitive lookup can't use it:
Seq Scan on customers (actual time=1.071..23.028 rows=1 loops=1)
Filter: (lower(email) = 'user4242@example.com'::text)
Rows Removed by Filter: 99999
Execution Time: 23.039 ms
Index the expression itself, and the query must use the same expression:
Index Scan using customers_email_lower_idx on customers (actual time=0.043..0.044 rows=1 loops=1)
Index Cond: (lower(email) = 'user4242@example.com'::text)
Execution Time: 0.065 ms
A partial index only includes rows matching a condition. A queue of pending orders is 4% of the table; index only those:
CREATE INDEX orders_pending_idx ON orders (created_at) WHERE status = 'pending';
Limit (actual time=0.013..0.035 rows=20 loops=1)
-> Index Scan using orders_pending_idx on orders (actual time=0.012..0.033 rows=20 loops=1)
Buffers: shared hit=17 read=2
Execution Time: 0.041 ms
The sizes of everything created so far:
index | size
orders_cust_created_incl_idx | 78 MB
orders_cust_created_idx | 61 MB
orders_pkey | 45 MB
orders_created_idx | 43 MB
orders_customer_idx | 16 MB
orders_status_idx | 13 MB
orders_pending_idx | 1768 kB
The partial index is 1.7 MB against 43 MB for the same column indexed in full, so it stays in memory easily and costs nothing when most rows are inserted. It's ideal for "work queue" queries: unprocessed jobs, unread notifications, open tickets.
Notice also that orders_status_idx is only 13 MB for 2 million rows. Since version 13, PostgreSQL's B-trees store a repeated key once with a list of row pointers (deduplication), which helps low-cardinality columns a lot.
And the skewed status column shows why the planner keeps per-value statistics: for 'refunded' (2,018 rows) the index is perfect, while 'delivered' (1.8 million rows) is most of the table. The same query shape needs different plans depending on the value. ORMs and prepared statements that reuse one generic plan can get this wrong.
The usual culprits, each measured with the relevant index in place:
| Query | Uses index? | Time |
|---|---|---|
WHERE lower(email) = ... with an index on email only |
No (seq scan) | 23 ms vs 0.07 ms |
WHERE email LIKE '%4242@Example.com' (leading wildcard) |
No (seq scan) | 7 ms |
WHERE date(created_at AT TIME ZONE 'UTC') = '2026-03-01' |
No (seq scan) | 217 ms |
WHERE created_at >= '2026-03-01' AND created_at < '2026-03-02' |
Yes | 0.38 ms |
WHERE customer_id + 0 = 4242 |
Scans the whole index | 71 ms |
WHERE customer_id::text = '4242' |
Scans the whole index | 133 ms |
WHERE customer_id = 4242 OR created_at >= ... |
Yes, both (BitmapOr) | 0.30 ms |
The pattern: the indexed column must appear on its own on one side of the comparison. Any function, arithmetic or cast applied to the column hides it from the index. Rewrite the condition so the work is done on the constant instead (the date range instead of date(...)), or build an expression index that matches exactly.
The ::text cast is how this usually happens in real life: an application or ORM sends a parameter of the wrong type, and the database casts the column instead of the parameter. Check parameter types when a query is fast in psql but slow from the application.
The last row busts a myth: an OR across two indexed columns doesn't force a sequential scan in PostgreSQL. It reads both indexes and combines the results in a bitmap.
Leading-wildcard LIKE needs a different kind of index: a trigram index (pg_trgm with GIN) for substring search, or a full-text index for words.
Every index must be updated on every insert, on deletes (eventually, via vacuum), and on any update that changes an indexed column. Inserting 200,000 rows in batches of 1,000 into copies of the table with more and more secondary indexes:
0 secondary indexes: insert 200k rows 1.14s ( 176109 rows/s) | update 50k rows 0.17s | index size 5512 kB vs table 26 MB
1 secondary indexes: insert 200k rows 1.31s ( 152947 rows/s) | update 50k rows 0.25s | index size 9792 kB vs table 26 MB
3 secondary indexes: insert 200k rows 1.53s ( 131090 rows/s) | update 50k rows 0.37s | index size 17 MB vs table 26 MB
6 secondary indexes: insert 200k rows 2.54s ( 78682 rows/s) | update 50k rows 0.76s | index size 41 MB vs table 26 MB
Six indexes more than halved insert throughput and made updates four times slower, and together they're bigger than the table. A second run was noisier (6 indexes: 49,000 rows per second, updates 1.6 s) but showed the same trend. Each index also takes buffer pool memory that the table could have used.
PostgreSQL has an optimisation called HOT (heap-only tuple) updates: if an update changes no indexed column and the new row version fits on the same page, no index needs touching at all. Indexing a frequently updated column (like a last_seen_at or a counter) disables HOT for those updates. Think twice before indexing hot columns.
Find indexes that don't pay their way:
SELECT relname AS table, indexrelname AS index, idx_scan AS scans, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes WHERE schemaname = 'public' ORDER BY idx_scan, pg_relation_size(indexrelid) DESC;
table | index | scans | size
customers | customers_email_idx | 1 | 3992 kB
customers | customers_email_lower_idx | 1 | 3992 kB
orders | orders_pending_idx | 1 | 1768 kB
orders | orders_status_idx | 2 | 13 MB
orders | orders_cust_created_idx | 4 | 61 MB
orders | orders_created_idx | 5 | 43 MB
customers | customers_city_idx | 8 | 696 kB
customers | customers_pkey | 12 | 2208 kB
orders | orders_customer_idx | 140 | 16 MB
orders | orders_pkey | 1912 | 45 MB
orders | orders_cust_created_incl_idx | 50014 | 78 MB
On a production database, indexes with zero or near-zero scans after weeks of traffic are candidates for removal (check replicas too, since statistics are per server, and keep indexes that enforce uniqueness). Also look for redundant indexes: here orders_cust_created_idx has the same leading columns as orders_cust_created_incl_idx, which can serve every query it can. orders_customer_idx on (customer_id) alone is also covered by the composite, which starts with customer_id.
The planner estimates how many rows each step returns from statistics about each column. With several conditions, it assumes the columns are independent and multiplies their selectivities. In this data, city determines country, so that assumption is false:
Aggregate (cost=1277.69..1277.70 rows=1 width=8) (actual rows=1 loops=1)
-> Bitmap Heap Scan on customers (cost=184.45..1264.05 rows=5455 width=0) (actual rows=16666 loops=1)
Recheck Cond: (city = 'Kathmandu'::text)
Filter: (country = 'NP'::text)
It estimated 5,455 rows (1/6 of customers are in Kathmandu × 1/3 are in Nepal) when the real answer is 16,666: everyone in Kathmandu is in Nepal. Errors like this multiply as they flow up the plan, into joins. Extended statistics tell the planner about the dependency:
CREATE STATISTICS customers_city_country (dependencies, mcv) ON city, country FROM customers;
ANALYZE customers;
Aggregate (cost=1315.39..1315.40 rows=1 width=8) (actual rows=1 loops=1)
-> Bitmap Heap Scan on customers (cost=189.54..1273.69 rows=16677 width=0) (actual rows=16666 loops=1)
16,677 estimated, 16,666 actual. Now the twist. Joining those customers to their orders:
| Setup | Plan chosen | Time |
|---|---|---|
| Wrong estimate (5,455 customers) | Nested loop: index lookup per customer | 127 ms |
| Correct estimate (16,677 customers) | Hash join: full scan of orders |
300 ms |
Correct estimate, random_page_cost = 1.1 |
Nested loop | 93 ms |
Fixing the estimate made the query slower. With the true row count, the planner calculated that 16,677 index lookups (each costed as random disk reads at random_page_cost = 4) would cost more than reading the whole table once. On spinning disks that might be true. On SSDs, or with the data in memory as here, random reads cost little more than sequential ones. Setting random_page_cost = 1.1, the usual recommendation for SSD storage, gives the planner a correct picture of both the data and the hardware, and it picks the fastest plan.
Two lessons. The planner can only be as good as its statistics and its cost settings. And when you change something and a query gets slower, don't assume your change was wrong: look at which other assumption it exposed.
pg_stat_statements and sort by total_exec_time. A 5 ms query run 10 million times a day matters more than a 10-second report run once.EXPLAIN (ANALYZE, BUFFERS) with realistic parameter values, ideally on production-sized data. Plans change with data size.loops into account.ANALYZE, raise the column's statistics target, add extended statistics, or rewrite the condition.Rows Removed by Filter, a Sort before a LIMIT, heap fetches in an index-only scan.INCLUDE the columns needed for an index-only scan if it's hot enough to justify the size.In production, CREATE INDEX CONCURRENTLY builds an index without blocking writes (it takes longer, and leaves an invalid index behind if it fails, so check). Plain CREATE INDEX blocks inserts, updates and deletes on the table until it finishes.
EXPLAIN (ANALYZE, BUFFERS). Compare estimated and actual rows; judge work by buffers.(user_id, created_at). Separate indexes produce a plan that's fast for most users and terrible for some.random_page_cost.