Indexes and EXPLAIN
A query that takes 2 ms with 1,000 rows can take 20 seconds with 10 million. The difference between a slow app and a fast one is usually a handful of well-chosen indexes, and the tool for choosing them is EXPLAIN.
What an index is
Without an index, finding email = 'x' means reading every row: a sequential scan. An index is a sorted structure (normally a B-tree) that points to rows, like the index at the back of a book. Finding a value takes a few steps even among millions of rows.
The trade-off: indexes take disk space and make every INSERT/UPDATE/DELETE slightly slower, because the index must be updated too. So you add the ones your queries need, not one per column.
A big table to experiment with
Every editor in this lesson starts with a users table of 200,000 rows, built with generate_series:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
status text NOT NULL,
signed_up timestamptz NOT NULL
);
INSERT INTO users (email, country, status, signed_up)
SELECT 'user' || i || '@example.com',
(ARRAY['IN','US','UK','DE','BR','JP'])[1 + i % 6],
CASE WHEN i % 50 = 0 THEN 'banned' ELSE 'active' END,
timestamptz '2024-01-01' + (i * interval '2 minutes')
FROM generate_series(1, 200000) AS i;
ANALYZE users;Reading EXPLAIN
EXPLAIN shows the plan: the steps Postgres will take. EXPLAIN ANALYZE actually runs the query and adds real timings:
How to read it:
- Seq Scan on users: it read the whole table.
- Rows Removed by Filter: 199999: it threw away almost everything it read. That's the classic sign an index is missing.
- cost=0.00..4466.00: the planner's estimate in arbitrary units (startup..total). Compare costs between plans, not to milliseconds.
- actual time=…: real milliseconds (only with
ANALYZE). - rows=1: estimated vs actual rows. Big mismatches mean stale statistics (run
ANALYZE).
Now add an index and run the same query:
Index Scan with a tiny execution time. On a real server the difference grows with table size: a seq scan gets linearly slower, an index lookup barely changes.
⚠️
EXPLAIN ANALYZEreally executes the statement. Wrap anUPDATEorDELETEinBEGIN; … ROLLBACK;when analysing it.
The main plan nodes
| Node | Meaning |
|---|---|
| Seq Scan | Read every row. Fine for small tables or when most rows match. |
| Index Scan | Walk the index, then fetch each matching row from the table. |
| Index Only Scan | Everything needed is in the index; the table isn't touched. Fastest. |
| Bitmap Index Scan + Bitmap Heap Scan | Collect many matches from the index, then read them in physical order. Medium selectivity. |
| Nested Loop / Hash Join / Merge Join | Three ways to join tables. |
| Sort, Aggregate, Limit | What they sound like. |
When Postgres ignores your index
An index helps only when a query matches few rows. If 98% of users are active, reading the whole table is cheaper than jumping around through an index:
The planner chooses using statistics about your data. That's why ANALYZE (run automatically by autovacuum) matters.
Functions on a column also prevent normal index use:
Composite indexes: column order matters
An index on (country, signed_up) is sorted by country first, then by date within each country, like a phone book sorted by surname then first name.
Rule of thumb: put columns you filter with = first, and range (>, <, BETWEEN) or ORDER BY columns after. A query on only the second column usually can't use the index efficiently (PostgreSQL 18 added a "skip scan" that helps when the first column has few distinct values).
Partial and covering indexes
A partial index only includes rows that match a condition. It's smaller and faster when you always query that subset:
A covering index stores extra columns with INCLUDE, enabling an Index Only Scan:
Other index types
| Type | Good for |
|---|---|
| B-tree (default) | =, <, >, BETWEEN, ORDER BY, LIKE 'abc%' |
| GIN | JSONB, arrays, full-text search (values containing many keys) |
| GiST | Ranges, geometry, exclusion constraints |
| BRIN | Huge tables where values follow the physical order (append-only timestamps) |
| Hash | Only =; rarely better than B-tree |
Indexes in production
- Create indexes on a live table with
CREATE INDEX CONCURRENTLY, which doesn't block writes (it can't run inside a transaction). - Find unused indexes, which cost writes for no benefit:
SELECT * FROM pg_stat_user_indexes WHERE idx_scan = 0; - Find your slowest queries with the
pg_stat_statementsextension, thenEXPLAIN ANALYZEthem. - Index your foreign-key columns: Postgres doesn't do it automatically.
Practice
- Run
EXPLAIN ANALYZE SELECT * FROM users WHERE country = 'JP' ORDER BY signed_up DESC LIMIT 10;and note the plan. - Create the index that makes it fast, and run it again.
- Try
WHERE signed_up::date = '2024-03-01'. Why can't it use an index onsigned_up? Rewrite it as a range so it can.
1.In EXPLAIN output, what suggests a missing index?
2.Why might Postgres ignore an index on status when 98% of rows are 'active'?
3.For WHERE country = 'IN' AND signed_up > '2024-06-01', which composite index is best?