Indexes and query plans
Without an index, the database answers where customer_id = 42 by reading every row in the table: a sequential scan. With 40 million orders, that’s slow no matter how fast the server is.
A B-tree index keeps the values of a column sorted, with pointers to the rows. Finding customer 42 takes a few steps, like looking up a word in a dictionary.
Indexes can cover several columns. An index on (customer_id, created_at) is sorted by customer first, then by date within each customer, like a phone book sorted by last name, then first name. That makes it perfect for “customer 42’s orders, newest first”, and useless for “all orders from yesterday”: you can’t use a phone book to find everyone named Ana.
To see what the database actually does, put EXPLAIN ANALYZE in front of a query. It shows the planQuery planThe steps a database chooses to execute a query (scans, index lookups, joins, sorts), shown with EXPLAIN.Open in glossary →: which index (if any) was used, how many rows each step produced, and how long it took.
PostgreSQL’s default B-tree supports equality, ranges, ORDER BY and prefix LIKE 'abc%' (with the right collation or text_pattern_ops). For composite indexes, put equality predicates first, then the range or sort column (the “ESR” rule: equality, sort, range), and include the tiebreaker for stable ordering; a query can use the index only through its leftmost columns. INCLUDE columns make index-only scans possible (helped by an up-to-date visibility map, i.e. vacuum). Partial indexes (where status = 'OPEN') index only hot rows; expression indexes (lower(email)) match queries that use the same expression. Index killers: functions or casts on the indexed column, leading wildcards, OR across different columns (sometimes rescued by bitmap OR), implicit type conversions, and low selectivity, where a scan is genuinely cheaper. Read plans with EXPLAIN (ANALYZE, BUFFERS): compare estimated vs actual rows (bad estimates → stale statistics or correlated columns; ANALYZE, extended statistics), find the node with the most time, and watch for Sort spilling to disk, nested loops over many rows, and Rows Removed by Filter. Indexes cost writes, disk and cache: drop unused ones (pg_stat_user_indexes.idx_scan = 0) and create new ones with CREATE INDEX CONCURRENTLY in production.
-- "My orders": one customer's orders, newest first, 50 at a time
select id, total, status, created_at
from orders
where customer_id = 42
order by created_at desc, id desc
limit 50;
-- Equality column first, then the sort columns in the same order and direction
create index concurrently orders_customer_created_idx
on orders (customer_id, created_at desc, id desc);
explain (analyze, buffers)
select id, total, status, created_at from orders
where customer_id = 42 order by created_at desc, id desc limit 50;-- Before the index:
Limit (actual time=3812.4..3812.4 rows=50 loops=1)
-> Sort (actual time=3812.4..3812.4 rows=50 loops=1)
Sort Key: created_at DESC, id DESC
-> Seq Scan on orders (rows=1840 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 39998160
-- After:
Limit (actual time=0.041..0.118 rows=50 loops=1)
-> Index Scan using orders_customer_created_idx on orders (rows=50 loops=1)
Index Cond: (customer_id = 42)
Buffers: shared hit=53- Before: a
Seq Scanread all 40 million rows, threw away 39,998,160 of them (Rows Removed by Filter), then sorted the rest: 3.8 seconds. - After: an
Index Scanjumps to customer 42’s entries, which are already sorted newest first, and stops after 50 rows: about 0.1 ms. No sort step at all. concurrentlybuilds the index without blocking writes to the table, which matters on a live system.
Predict the output
With only the index (customer_id, created_at desc, id desc), a report runs: select count(*) from orders where created_at >= now() - interval '1 day'. Can it use the index efficiently?
The index is sorted by customer first. Yesterday's orders are scattered across every customer's section, like everyone named Ana in a phone book sorted by last name. A query must constrain the leftmost column(s) to seek into a B-tree. For time-based reports, add a separate index on created_at (or a BRIN index for append-only time data), if the report is important enough to pay for another index.
Tap the line with the bug.
// index: create index orders_created_idx on orders (created_at);
@Query(
value = """
select * from orders
where date(created_at) = :day
""",
nativeQuery = true,
)
fun ordersOn(day: LocalDate): List<Order>// index: create index orders_created_idx on orders (created_at);
@Query(value = """
select * from orders
where date(created_at) = :day
""", nativeQuery = true)
List<Order> ordersOn(LocalDate day);Hint: What does the index contain, and what does the query compare?
The index stores created_at values, but the query compares date(created_at), a computed value. The database can’t use the index to find rows whose computed date matches, so it scans the table and computes date() for every row.
Rewrite the condition as a range on the column itself:
@Query(
value = """
select * from orders
where created_at >= :start and created_at < :end
""",
nativeQuery = true,
)
fun ordersBetween(start: Instant, end: Instant): List<Order> // start = day at 00:00, end = next day at 00:00@Query(value = """
select * from orders
where created_at >= :start and created_at < :end
""", nativeQuery = true)
List<Order> ordersBetween(Instant start, Instant end); // start = day at 00:00, end = next day at 00:00(An expression index on date(created_at) would also work, but ranges keep one index useful for many queries. Mind the time zone when computing day boundaries.)
Reading plans quickly
| Plan node | Means | Look at |
|---|---|---|
| Seq Scan | Reads the whole table | Fine for small tables or large fractions; bad with a selective filter |
| Index Scan / Index Only Scan | Seeks via an index (only-scan avoids the table) | Heap Fetches on index-only scans (vacuum) |
| Bitmap Heap Scan | Collects matches from one or more indexes, then reads pages | Good for medium selectivity and ORs |
| Nested Loop | For each outer row, look up inner rows | Fine with few outer rows and an index on the inner side |
| Hash Join / Merge Join | Join large sets | work_mem spills (Batches > 1) |
| Sort | Explicit sort | Sort Method: external merge means it spilled to disk |
Estimated vs actual rows that differ by orders of magnitude are the root of most bad plans: refresh statistics (ANALYZE), raise the statistics target for skewed columns, or add extended statistics for correlated columns. Use pg_stat_statements to find which queries consume the most total time; optimize those, not the slowest single query you happen to notice.
Choose the index
A support tool searches tickets: select * from tickets where status = 'OPEN' and assignee_id = ? order by priority desc, created_at limit 20. 95% of tickets are closed. Which index would you create?
›
Which columns are compared with =, and which decide the order? Do you need closed tickets in the index at all?
SolutionTry it yourself first
A partial composite index that matches the query:
create index concurrently tickets_open_assignee_idx
on tickets (assignee_id, priority desc, created_at)
where status = 'OPEN';assignee_idfirst (equality), thenpriority desc, created_atin the query’s sort order, so no sort step is needed and thelimitstops early.where status = 'OPEN'keeps only 5% of tickets in the index: it’s small, stays in memory, and costs nothing when closed tickets are written.- The query must include
status = 'OPEN'for the database to use a partial index, which it does.
- B-tree: equality, range, sort, prefix LIKE. Composite: equality → sort → range (ESR); only leftmost-prefix queries seek.
INCLUDEfor index-only scans; partial indexes for hot subsets; expression indexes must match the query expression.- Killers: functions/casts on indexed columns (
date(col)), leading wildcards, type mismatches, low selectivity. EXPLAIN (ANALYZE, BUFFERS): estimated vs actual rows, the costliest node, sorts spilling, rows removed by filter.pg_stat_statementsfor total time.- Indexes cost writes and memory: drop unused ones;
CREATE INDEX CONCURRENTLYin production.
Check this part
What does a Seq Scan in a query plan mean?
An index exists on email. Why can't where lower(email) = ? use it?
For where tenant_id = ? and status = ? order by created_at desc, which column order is best?
Estimated rows: 10, actual rows: 2,000,000 on a join. Likely cause?