PostgreSQL Indexes & EXPLAIN
An index is a separate data structure that helps PostgreSQL find rows without reading the whole table, much like the index at the back of a book. Indexes make lookups, joins and sorting dramatically faster on large tables. They cost disk space and slow down writes a little, because every insert and update must also update the index.
Seeing the plan with EXPLAIN
EXPLAIN shows the query plan: the steps PostgreSQL has chosen to run a query. Normally it also prints cost estimates; EXPLAIN (COSTS OFF) hides them so we can focus on the shape of the plan.
The sample tables are tiny, so let's build a bigger one: 50,000 page views of our 20 books.
CREATE TABLE page_views (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id integer NOT NULL,
viewed_on date NOT NULL
);
INSERT INTO page_views (book_id, viewed_on)
SELECT (n % 20) + 1, DATE '2024-01-01' + (n % 366)
FROM generate_series(1, 50000) AS n;
ANALYZE page_views;
EXPLAIN (COSTS OFF)
SELECT count(*) FROM page_views WHERE book_id = 7;CREATE TABLE
INSERT 0 50000
ANALYZE
QUERY PLAN
-------------------------------
Aggregate
-> Seq Scan on page_views
Filter: (book_id = 7)
(3 rows)
Seq Scan means a sequential scan: PostgreSQL reads all 50,000 rows and applies the filter to each one. (ANALYZE collects statistics about the data, which the planner uses to estimate how many rows each step will produce.)
CREATE INDEX
CREATE TABLE page_views (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id integer NOT NULL,
viewed_on date NOT NULL
);
INSERT INTO page_views (book_id, viewed_on)
SELECT (n % 20) + 1, DATE '2024-01-01' + (n % 366)
FROM generate_series(1, 50000) AS n;
CREATE INDEX page_views_book_id_idx ON page_views (book_id);
ANALYZE page_views;
EXPLAIN (COSTS OFF)
SELECT count(*) FROM page_views WHERE book_id = 7;
EXPLAIN (COSTS OFF)
SELECT * FROM page_views WHERE id = 42;CREATE TABLE
INSERT 0 50000
CREATE INDEX
ANALYZE
QUERY PLAN
---------------------------------------------------------
Aggregate
-> Bitmap Heap Scan on page_views
Recheck Cond: (book_id = 7)
-> Bitmap Index Scan on page_views_book_id_idx
Index Cond: (book_id = 7)
(5 rows)
QUERY PLAN
------------------------------------------------
Index Scan using page_views_pkey on page_views
Index Cond: (id = 42)
(2 rows)
Now the plan uses the index. For the 2,500 matching rows it chooses a bitmap scan: first collect the matching row locations from the index, then read those table pages in order. For a single row (id = 42) it uses a plain index scan on the primary key's index, which PostgreSQL creates automatically for every PRIMARY KEY and UNIQUE constraint.
Note: On small tables the planner often ignores indexes on purpose: reading a few pages sequentially is cheaper than jumping through an index. So when a plan on a tiny table shows a
Seq Scanalthough an index exists, that is usually the right choice, not a problem to fix.
EXPLAIN ANALYZE
EXPLAIN ANALYZE actually runs the query and adds real row counts. Timing varies from run to run, so here we switch it off:
CREATE TABLE page_views (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, book_id integer NOT NULL);
INSERT INTO page_views (book_id) SELECT (n % 20) + 1 FROM generate_series(1, 50000) AS n;
CREATE INDEX ON page_views (book_id);
ANALYZE page_views;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*) FROM page_views WHERE book_id = 7;CREATE TABLE
INSERT 0 50000
CREATE INDEX
ANALYZE
QUERY PLAN
---------------------------------------------------------------------------------------
Aggregate (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on page_views (actual rows=2500.00 loops=1)
Recheck Cond: (book_id = 7)
Heap Blocks: exact=271
-> Bitmap Index Scan on page_views_book_id_idx (actual rows=2500.00 loops=1)
Index Cond: (book_id = 7)
Index Searches: 1
(7 rows)
Comparing estimated rows with actual rows is the first step in diagnosing a slow query.
Warning:
EXPLAIN ANALYZEon anUPDATEorDELETEreally changes the data. Wrap it inBEGIN; … ROLLBACK;when you only want to look.
Kinds of indexes
| Index | Created with | Good for |
|---|---|---|
| B-tree (default) | CREATE INDEX … (col) |
=, <, >, BETWEEN, ORDER BY, LIKE 'abc%' |
| Multi-column | (a, b) |
conditions on a, or on a and b (leftmost columns first) |
| Unique | CREATE UNIQUE INDEX |
enforcing uniqueness |
| Expression | (lower(email)) |
queries that filter on that exact expression |
| Partial | … WHERE status = 'pending' |
indexing only the rows you query often |
| GIN | USING gin (tags) |
arrays, jsonb, full-text search |
| GiST / BRIN / hash | USING gist … |
ranges and geometry / huge append-only tables / equality only |
Expression and partial indexes
An index on email doesn't help WHERE lower(email) = …, because the expression is different. An expression index stores the computed value:
CREATE TABLE users AS
SELECT n AS id, 'User' || n || '@Example.com' AS email
FROM generate_series(1, 20000) AS n;
CREATE INDEX users_email_idx ON users (email);
CREATE INDEX users_email_lower_idx ON users (lower(email));
CREATE UNIQUE INDEX users_id_idx ON users (id) WHERE id > 19000;
ANALYZE users;
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE lower(email) = 'user77@example.com';
SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'users' ORDER BY indexname;SELECT 20000
CREATE INDEX
CREATE INDEX
CREATE INDEX
ANALYZE
QUERY PLAN
-----------------------------------------------------------
Index Scan using users_email_lower_idx on users
Index Cond: (lower(email) = 'user77@example.com'::text)
(2 rows)
indexname | indexdef
-----------------------+--------------------------------------------------------------------------------------
users_email_idx | CREATE INDEX users_email_idx ON public.users USING btree (email)
users_email_lower_idx | CREATE INDEX users_email_lower_idx ON public.users USING btree (lower(email))
users_id_idx | CREATE UNIQUE INDEX users_id_idx ON public.users USING btree (id) WHERE (id > 19000)
(3 rows)
pg_indexes lists the indexes of a table (psql's \di shows the same). The last index is partial: it only covers ids above 19000.
Rules of thumb
- Index columns that appear in frequent
WHERE,JOIN … ONandORDER BYclauses, and foreign key columns. - Don't index everything: each index slows down inserts and updates and uses space.
- Check with
EXPLAINthat a new index is actually used, and drop unused ones (DROP INDEX name). CREATE INDEX CONCURRENTLYbuilds an index without blocking writes on a busy production table.
Test yourself
What does Seq Scan in a query plan mean?
- An index is used
- Every row of the table is read
- The query is cached
- Rows are sorted
Which statement really executes the query while showing the plan?
- EXPLAIN
- EXPLAIN (COSTS OFF)
- EXPLAIN ANALYZE
- ANALYZE TABLE
Queries filter on lower(email). Which index helps?
- CREATE INDEX ON users (email)
- CREATE INDEX ON users (lower(email))
- CREATE INDEX ON users USING gin (email)
- None can