Skip to content
Commitwise
Menu
Databases

Indexes and query plans

How a B-tree index finds rows in a few page reads, why wrapping a column in a function hides it from the index, composite index column order, partial, expression and covering indexes, and how to read EXPLAIN ANALYZE to see why a query is slow and why the planner sometimes ignores your index.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The orders page took 30 milliseconds at launch and takes 9 seconds a year later. Nobody changed the code; the table just grew from 10,000 rows to 40 million. One CREATE INDEX brings it back to 2 milliseconds. Another index, added “just in case”, slows every checkout.

“How would you speed up this slow query?” is asked in almost every backend interview, and the answer always involves indexes and query plans. This lesson covers how indexes work in any relational database, with PostgreSQL’s EXPLAIN as the tool. The Spring-specific side (Hibernate queries, pagination, batching) is in Database performance.

New to some of these? Open what you need, or skip ahead.

Basics:What the database does with your SQL

SQL says what you want; the database’s planner decides how: read the whole table, or jump to the rows through an index, and in which order to join tables. Data lives in 8 KB pages on disk, cached in memory. See How relational databases work.

Basics:SELECT, WHERE, ORDER BY and JOIN

WHERE filters rows, ORDER BY sorts them, LIMIT cuts the result, and JOIN … ON matches rows of two tables, usually foreign key = primary key. See SQL basics and Joins.

Part Not started

How an index finds rows

Without an index, finding email = 'ana@example.com' means reading every row of customers and checking each one. That’s a sequential scan: fine for 1,000 rows, slow for 50 million.

A database indexDatabase indexA sorted structure on one or more columns that lets the database find rows without reading the whole table.Open in glossary → works like the index at the back of a book: a sorted list of values, each pointing to where the row is. Because it’s sorted, the database can jump to the right place instead of reading everything. Most indexes are a B-treeB-treeThe sorted, shallow tree most database indexes use, so a lookup reads a few pages even in a huge table.Open in glossary →, a sorted tree only 3 or 4 levels deep even for millions of rows, so a lookup reads a handful of pages.

CREATE INDEX orders_customer_id ON orders (customer_id);

An index on a column helps:

  • WHERE customer_id = 42 (equality)
  • WHERE created_at >= '2026-11-01' (ranges, BETWEEN, <, >)
  • ORDER BY created_at (the index is already sorted)
  • JOIN … ON o.customer_id = c.id (finding the matching rows)

It isn’t free. Every INSERT, UPDATE and DELETE must update every index on the table too, and indexes take disk space. So you add them for the queries the app actually runs, not for every column.

Primary keys and UNIQUE columns get an index automatically. Foreign keys don’t, in PostgreSQL.

One rule catches everyone: the index is on the column, not on what you compute from it. WHERE lower(email) = 'ana@example.com' or WHERE created_at::date = '2026-11-14' asks about a calculated value that isn’t in the index, so the database falls back to reading the whole table.

B-tree internals: pages of sorted keys; inner pages fan out to hundreds of children, so depth stays 3 to 4 for hundreds of millions of rows. Leaf pages are linked, which makes range scans and ordered reads sequential. A leaf entry holds the key and the row’s location (TID); PostgreSQL then fetches the row from the heap (an Index Scan), unless every needed column is in the index and the page is marked all-visible (an Index Only Scan). Many matching rows on scattered pages → a Bitmap Heap Scan, which sorts locations first to read each page once.

Index types (PostgreSQL):

TypeFor
B-treeequality, ranges, sorting, LIKE 'abc%'; the default
Hashequality only; rarely better than B-tree
GIN“contains”: jsonb @>, arrays, full-text search, trigram LIKE '%x%'
GiST / SP-GiSTranges, geometry, nearest-neighbor, exclusion constraints
BRINhuge append-only tables whose order follows a column (time series); tiny

Costs: write amplification (every index updated per insert; an update to any indexed column creates new index entries; PostgreSQL’s HOT updates avoid that only when no indexed column changes and the page has room), bloat, more WAL and replication traffic, planner time. Find unused indexes with pg_stat_user_indexes.idx_scan = 0 (check replicas too before dropping).

Sargability: a predicate can use an index only when the indexed expression appears bare on one side. lower(email) needs an expression index ON customers (lower(email)); created_at::date = d becomes created_at >= d AND created_at < d + 1; implicit casts (comparing a text column to a number, varchar to nvarchar in SQL Server) silently disable indexes.

Predict the output

customers has 5 million rows and a UNIQUE index on email. Which plan does this query get?

EXPLAIN SELECT id FROM customers WHERE lower(email) = 'ana@example.com';
-- joins and "orders of this customer"
CREATE INDEX orders_customer_id ON orders (customer_id);

-- case-insensitive login lookup
CREATE UNIQUE INDEX customers_email_lower ON customers (lower(email));

-- "today's orders", written so the index can be used
CREATE INDEX orders_created_at ON orders (created_at);
SELECT id, total FROM orders
WHERE created_at >= date '2026-11-14' AND created_at < date '2026-11-15';

-- on a live production table: build without blocking writes
CREATE INDEX CONCURRENTLY order_items_product_id ON order_items (product_id);

The index that’s there but not used

Spot the bugOrders placed on one day

Tap the line with the bug.

CREATE INDEX orders_created_at ON orders (created_at);

-- admin page: all orders from a chosen day
SELECT id, customer_id, total
FROM orders
WHERE date(created_at) = '2026-11-14'
ORDER BY created_at;

Deep diveIndex-only scans and covering indexesInterview favorite

An order history endpoint runs SELECT id, status, total FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 with an index on (customer_id, created_at). The plan is an Index Scan: 20 index entries, then 20 heap fetches on 20 different pages, often cold. At 3,000 requests per second, those random heap reads dominate.

A covering index stores the extra columns in the index leaves so the heap isn’t needed:

CREATE INDEX CONCURRENTLY orders_customer_recent
    ON orders (customer_id, created_at DESC)
    INCLUDE (status, total);

INCLUDE (PostgreSQL 11+, SQL Server) adds payload columns that aren’t part of the sort key, so they don’t affect ordering or uniqueness. The plan becomes an Index Only Scan, with one caveat specific to PostgreSQL: MVCC visibility lives in the heap, so an index-only scan still visits the heap for pages not marked all-visible in the visibility map. EXPLAIN (ANALYZE) shows this as Heap Fetches: N. On a hot, frequently updated table, aggressive autovacuum keeps that number low; if it stays high, the covering index buys little.

Trade-offs to mention: wider indexes mean more memory and slower writes, and INCLUDE columns that change often (like status) generate new index entries on every update and prevent HOT updates. Cover the queries that are hot and stable, not every query.

  • B-tree: depth 3–4, linked leaves for ranges and ordering; Index Scan → heap, Index Only Scan (visibility map), Bitmap Heap Scan for many rows.
  • GIN for jsonb/arrays/full-text/trigram, GiST for ranges/geo, BRIN for append-only time series.
  • Sargable predicates only: expression indexes (lower(email)), ranges instead of ::date, watch implicit casts.
  • Every index costs writes, WAL and HOT updates; drop unused ones (idx_scan = 0, check replicas). CREATE INDEX CONCURRENTLY in production.
CREATE INDEX CONCURRENTLY orders_customer_recent
    ON orders (customer_id, created_at DESC) INCLUDE (status, total);
CREATE INDEX ON customers (lower(email));
CREATE INDEX ON events USING brin (created_at);
CREATE INDEX ON products USING gin (attributes jsonb_path_ops);

Check this part

  1. Why does an index make WHERE customer_id = 42 fast?

  2. There is an index on created_at. Can WHERE created_at::date = '2026-11-14' use it?

  3. An Index Only Scan shows Heap Fetches: 9500 out of 10000 rows. Why?

  4. Which index type fits WHERE attributes @> '{"color": "red"}' on a jsonb column?

An index is a sorted copy of some columns with pointers to the rows, usually a B-tree, so lookups, ranges, sorts and joins read a few pages instead of the whole table. Indexes cost write time and space. A function or cast on the indexed column hides it from the index; use an expression index or rewrite the condition.

Part Not started

Composite indexes and column order

An index can cover several columns. Think of a phone book sorted by last name, then by first name. It’s great for:

  • finding everyone named “Petrović” (the first column), and
  • finding “Petrović, Ana” (the first and the second column).

It’s useless for finding everyone named “Ana” regardless of last name: the Anas are scattered across the whole book.

A composite index works the same way:

CREATE INDEX orders_customer_created ON orders (customer_id, created_at);
QueryCan use the index?
WHERE customer_id = 42yes, the first column
WHERE customer_id = 42 AND created_at >= '2026-11-01'yes, both columns
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10yes, and no sorting needed: the 10 rows are read straight from the index
WHERE created_at >= '2026-11-01'not efficiently: it’s the second column

So the order of columns matters. A good default: columns compared with = first, then the one used for a range or for sorting.

An index on (customer_id, created_at) also makes a separate index on just (customer_id) unnecessary: the composite one already starts with it.

  • Leftmost prefix: a B-tree on (a, b, c) is ordered by a, then b within a, then c. It serves equality on a, a,b, a,b,c; ranges on the last used column; and ORDER BY that matches the column order (or its exact reverse). Equality columns first, then one range or sort column; columns after a range can only be filtered, not seeked. PostgreSQL 18 adds skip scan, which can use a later column when the leading one has few distinct values; Oracle and MySQL 8 have similar features. Don’t design around it.
  • Sort direction matters only for mixed orders: ORDER BY a ASC, b DESC needs an index (a, b DESC).
  • Partial indexes: CREATE INDEX … ON tickets (assignee_id, priority) WHERE status = 'OPEN' indexes only the 2% of rows you query, staying small and hot. The query’s WHERE must imply the index predicate.
  • Selectivity: an index on is_active (two values, 95% true) is rarely used for the common value; the planner reads the table instead. As the second column of a composite, or as a partial-index predicate, low-cardinality columns are useful.
  • Redundancy: (a) is redundant next to (a, b), except when the narrower index is much smaller and hot, or enforces uniqueness.
  • Multiple indexes vs one composite: PostgreSQL can combine single-column indexes with a BitmapAnd, but a matching composite index is usually far cheaper.
  • Interview method for “which index for this query?”: equality predicates → range/sort → LIMIT; then check selectivity, write load and whether an existing index already covers it.

Predict the output

There is an index on orders (customer_id, created_at). Customer 42 has 3,000 orders. What does the database do for this query?

SELECT id, total, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;
-- a customer's orders, newest first
CREATE INDEX orders_customer_created ON orders (customer_id, created_at DESC);

-- the support queue: open tickets per agent by priority; only open ones are indexed
CREATE INDEX tickets_open_queue ON tickets (assignee_id, priority DESC, created_at)
WHERE status = 'OPEN';

SELECT id, subject FROM tickets
WHERE status = 'OPEN' AND assignee_id = 7
ORDER BY priority DESC, created_at
LIMIT 20;

Practice: pick the indexes

Exercisemedium

Three queries, which indexes?

The shop runs these queries all day. Propose the fewest indexes that make all three fast, and say which query each one serves.

  1. SELECT * FROM orders WHERE customer_id = $1 AND status = 'PAID' ORDER BY created_at DESC LIMIT 20;
  2. SELECT * FROM orders WHERE customer_id = $1;
  3. SELECT * FROM order_items WHERE product_id = $1;
›

Query 1 has two equality conditions and one sort column. Which order of columns lets the database read 20 entries and stop?

›

Does query 2 need its own index if another index already starts with customer_id?

SolutionTry it yourself first
CREATE INDEX orders_customer_status_created
    ON orders (customer_id, status, created_at DESC);     -- queries 1 and 2

CREATE INDEX order_items_product_id
    ON order_items (product_id);                          -- query 3

Query 1: both equality columns first (customer_id, status), then the sort column, so the database jumps to “customer X, PAID” and reads the newest 20 entries in order. Query 2 uses the same index, because it starts with customer_id. Query 3 needs its own index: order_items’ primary key is (order_id, product_id), and product_id is its second column, so that index can’t find rows by product.

Deep diveAn index for every column: what goes wrongInterview favorite

A team reacts to slow queries by indexing every column of orders one by one: customer_id, status, created_at, total, country, coupon_code… Nine indexes later:

  • Checkout got slower. Each INSERT INTO orders now writes ten B-trees, and each status change (NEW → PAID → SHIPPED) updates the status index and loses HOT updates, so every other index gets a new entry too. WAL volume triples and replicas lag at peak.
  • The slow query is still slow. WHERE customer_id = $1 AND status = 'PAID' ORDER BY created_at DESC LIMIT 20 can use only one of the single-column indexes efficiently (or combine two with a BitmapAnd, which can’t return rows in created_at order, so it sorts). The composite index that matches it was never created.
  • Several indexes are never used: total and coupon_code have idx_scan = 0 after a month, status alone has four values and isn’t selective.

The fix is to design from queries, not columns: list the top queries by total time (pg_stat_statements), design one composite or partial index per query shape, check plans, then drop indexes that no query uses (after checking replicas and monthly jobs). A typical OLTP table ends up with a handful of well-chosen indexes. Interviewers want to hear that indexes are a trade-off with write cost, chosen per query, verified with EXPLAIN.

  • Leftmost prefix; equality columns first, then one range/sort column; match mixed sort directions. PostgreSQL 18 skip scan is a bonus, not a design tool.
  • Partial indexes for hot subsets (WHERE status = 'OPEN'); low-cardinality columns go second or into the predicate.
  • (a) is redundant next to (a, b); composite beats BitmapAnd of singles, especially with ORDER BY … LIMIT.
  • Design from top queries (pg_stat_statements), not columns; every index has a write cost.

Check this part

  1. An index on (customer_id, created_at). Which query cannot use it efficiently?

  2. For WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 10, which index fits best?

  3. When is a partial index like ... WHERE status = 'OPEN' a good idea?

  4. What is the main cost of adding many indexes to a write-heavy table?

A composite index is sorted by its first column, then the second inside it, like a phone book. It serves queries on a leftmost prefix of its columns. Put equality columns first, then the range or sort column. Partial indexes cover only the rows you query; low-selectivity columns alone rarely deserve an index.

Part Not started

Reading EXPLAIN

EXPLAIN shows the plan the database would use. EXPLAIN ANALYZE runs the query and adds what really happened: time and number of rows for each step.

EXPLAIN ANALYZE
SELECT c.name, o.total
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '1 day';
Hash Join  (cost=48.1..1210.6 rows=980 width=40) (actual time=0.9..6.8 rows=1012 loops=1)
  Hash Cond: (o.customer_id = c.id)
  ->  Index Scan using orders_created_at on orders o  (actual time=0.03..2.1 rows=1012 loops=1)
        Index Cond: (created_at >= (now() - '1 day'::interval))
  ->  Hash  (actual time=0.8..0.8 rows=2000 loops=1)
        ->  Seq Scan on customers c  (actual time=0.01..0.4 rows=2000 loops=1)
Planning Time: 0.2 ms
Execution Time: 7.1 ms

How to read it:

  1. Start from the most indented lines. They run first and feed the line above them. Here: scan orders through an index, scan customers, then join them.
  2. Know the main steps. Seq Scan reads the whole table. Index Scan uses an index. Hash Join, Nested Loop and Merge Join are ways to join. Sort sorts.
  3. Compare rows= (the estimate) with actual … rows=. If the database expected 10 rows and got 1,000,000, it probably chose a bad plan.
  4. Look at actual time to find the step where the time goes.

A Seq Scan isn’t always bad. On a small table, or when a query wants most of the rows, reading everything in order is faster than jumping around an index.

Careful: EXPLAIN ANALYZE really runs the statement. For an UPDATE or DELETE, wrap it in BEGIN; … ROLLBACK;.

What to look for in EXPLAIN (ANALYZE, BUFFERS):

  • Estimate vs actual rows at the lowest node where they diverge by orders of magnitude. Causes: stale statistics (ANALYZE), correlated columns (CREATE STATISTICS … (dependencies) on city, country), skewed values beyond default_statistics_target, functions the planner can’t see through, and generic plans for prepared statements.
  • loops=N: per-loop numbers are averages, so actual time and rows must be multiplied by loops. A Nested Loop with 200,000 inner loops is the classic N+1 inside the database.
  • Rows Removed by Filter: an index found many rows and most were thrown away. A better (composite or partial) index would filter earlier.
  • Sort Method: external merge Disk: 120MB: the sort spilled; raise work_mem for that query or avoid the sort with an index. Same for hash joins with Batches: 16.
  • Buffers: shared hit=… read=…: hits come from cache, reads from disk or the OS cache; cold-cache timings vary a lot.
  • Heap Fetches on index-only scans, and JIT time on short queries (sometimes worth disabling for OLTP).
  • Finding the queries: pg_stat_statements (top by total_exec_time), auto_explain with log_min_duration to capture plans of slow queries in production, log_lock_waits for blocking rather than slow plans.
  • Prepared statements: after five executions PostgreSQL may switch to a generic plan that ignores parameter values; for skewed data, plan_cache_mode = force_custom_plan. SQL Server’s “parameter sniffing” is the same family of problems.

Predict the output

orders has an index on status. 90% of orders are DELIVERED. Why might the planner pick a Seq Scan for this query?

EXPLAIN SELECT * FROM orders WHERE status = 'DELIVERED';
-- Seq Scan on orders  (cost=0.00..890112.00 rows=36000000 width=72)
--   Filter: (status = 'DELIVERED'::text)
-- the plan with real timings and cache usage
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total FROM orders
WHERE customer_id = 42 AND status = 'PAID'
ORDER BY created_at DESC LIMIT 20;

-- a write, measured without keeping its effect
BEGIN;
EXPLAIN ANALYZE UPDATE orders SET status = 'CANCELLED' WHERE created_at < now() - interval '30 days' AND status = 'NEW';
ROLLBACK;

-- refresh statistics after a big load
ANALYZE orders;

-- which queries cost the most in total (needs the pg_stat_statements extension)
SELECT query, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 1) AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Worked example: from slow to fast

The “my orders” page is slow for customers with long histories. Here’s how you’d investigate, step by step.

  1. Reproduce with real values. Pick a customer with many orders, say 42, and run the page’s query with EXPLAIN ANALYZE.
  2. Read the plan. It shows Seq Scan on orders … Filter: (customer_id = 42) … Rows Removed by Filter: 39998000, then a Sort. The database read all 40 million orders to find 2,000, then sorted them to return 20.
  3. Find what’s missing. The query filters on customer_id and sorts by created_at. There’s no index starting with customer_id.
  4. Add the index that matches the query. CREATE INDEX CONCURRENTLY orders_customer_created ON orders (customer_id, created_at DESC); (CONCURRENTLY so checkout keeps working while it builds).
  5. Check again. The new plan: Limit → Index Scan using orders_customer_created … rows=20. No Sort, execution time from 9 seconds to under a millisecond.
  6. Check the other side. The index makes every insert into orders a little slower. For a table that’s read far more often than written, that’s a good trade.
Deep diveThe query that was fast yesterdayInterview favorite

Nothing was deployed, and since 03:00 a report query takes 40 seconds instead of 200 ms. Typical causes and how to tell them apart:

  • Plan flip from statistics. A nightly bulk load added millions of rows; autovacuum’s ANALYZE hasn’t run, so the planner still thinks a filter returns 50 rows and picks a Nested Loop that now runs 2 million loops. Evidence: estimate vs actual mismatch at the bottom of the plan. Fix: ANALYZE after bulk loads, as a step of the job.
  • Generic plan for a prepared statement. The app’s driver prepares the statement; after a few executions the server switches to a generic plan chosen for “average” parameters, terrible for the big customer. Evidence: fast in psql with literal values, slow from the app. Fix: plan_cache_mode = force_custom_plan for that role/query, or restructure.
  • Data distribution changed. A new status value or a giant tenant makes the old index unselective for some parameters.
  • Not the plan at all. The same plan, but waiting: pg_stat_activity.wait_event shows Lock (blocked by a migration or a long transaction), IO (cache was evicted, a replica serving cold), or CPU saturation from something else. EXPLAIN ANALYZE alone won’t show lock waits.
  • Bloat. A table updated constantly while a long transaction blocked vacuum: the same index scan now reads 10× more pages. BUFFERS numbers grow while row counts don’t.

A structured answer: confirm with pg_stat_statements when the mean time changed, capture the slow plan (auto_explain), compare with the good one, check waits, then fix the cause (statistics, index, query shape) rather than adding a hint or bumping hardware.

  • EXPLAIN (ANALYZE, BUFFERS); read bottom-up; find the lowest estimate/actual mismatch; multiply by loops.
  • Red flags: Seq Scan on large tables with few matches, Rows Removed by Filter, sorts/hashes spilling to disk, huge inner loops.
  • Stale stats (ANALYZE after loads), correlated columns (CREATE STATISTICS), generic plans (plan_cache_mode).
  • Find culprits with pg_stat_statements and auto_explain; check waits in pg_stat_activity before blaming the plan.

Check this part

  1. What does EXPLAIN ANALYZE do that EXPLAIN does not?

  2. Is a Seq Scan always a problem?

  3. A plan node estimates rows=12 but actual rows=850000. What does it suggest?

  4. A query is fast in psql with literal values but slow from the app. A likely cause?

EXPLAIN shows the plan; EXPLAIN ANALYZE runs the query and adds real times and row counts. Read nodes from the innermost up, compare estimated and actual rows, and look for Seq Scans on big tables, sorts spilling to disk and loops. A Seq Scan is the right plan when most rows match.

Key takeaways

  • An index is a sorted copy of some columns that lets the database jump to rows instead of reading the whole table.
  • Indexes speed up reads and slow down writes: add them for the queries you actually run.
  • A function or cast on the column (lower(email), created_at::date) hides it from the index. Use ranges or an expression index.
  • A composite index works like a phone book: it helps queries on its first column, or first and second, not on the second alone.
  • EXPLAIN ANALYZE shows the real plan: read from the inside out, compare estimated and actual rows.
  • B-tree mechanics: heap fetches vs index-only scans and the visibility map; INCLUDE for covering indexes; GIN, GiST, BRIN for other shapes.
  • Composite order: equality, then one range/sort column; partial indexes for hot subsets; design from query shapes.
  • Plans go wrong through statistics, correlation, generic plans and bloat; pg_stat_statements, auto_explain, BUFFERS find them.
  • CREATE INDEX CONCURRENTLY in production, and drop unused indexes deliberately.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.