Lesson 15 of 29Indexes and query performance
Composite, Covering and Partial Indexes
Order multi-column index keys correctly, let one index filter, sort and answer a query alone, and use partial and expression indexes to stay small.
The "My orders" page runs one query on every load: this customer's orders with a given status, newest first, twenty at a time. Someone has already added an index on customer_id, another on status and another on created_at, and the query is still slow, because the database can use at most one of them well and then has to sort the rest. One index with the right three columns in the right order would serve it in a handful of page reads, already sorted. Designing that index is one of the highest-value skills in backend work, and it is a favourite interview topic because it shows whether you understand what an index really is. This lesson builds on How Indexes Work.
A composite index is sorted by several columns
A composite (multi-column) index on (customer_id, created_at) is one B-tree whose keys are pairs. It sorts by customer_id first and, among rows with the same customer_id, by created_at. A phone book sorted by last name and then first name is the usual picture: finding every "Smith" is easy, finding "Smith, Jane" is easier, but finding everyone called "Jane" means reading the whole book.
Each entry is customer_id|created_at. Sorted by customer first, then by date within each customer.
That gives the leftmost-prefix rule: an index on (a, b, c) can seek on a, on a and b, or on all three, but not on b or c alone. The order of conditions in your WHERE clause does not matter; the planner matches columns, not text position.
Press Run (⌘ Enter) to see what happens.The text in brackets after USING INDEX tells you which columns were used to seek. Look at the fourth query. It filters on customer_id and created_at, but the plan seeks only on customer_id=?. The missing middle column, status, breaks the chain: inside customer 42, the entries are sorted by status first, so the dates are not in one run. The database reads all of customer 42's entries and checks the date on each. It still works, but it reads more than it needs. The last two queries skip the first column entirely and fall back to a full scan.
Why not one index per column? A plan normally uses one index per table access. Postgres can combine single-column indexes with a BitmapAnd, building a bitmap of matching pages from each index and intersecting them, but that reads several indexes and still cannot return rows in a useful order. A composite index designed for the query beats it.
Choosing the column order
For a single query, the reliable rule is:
- Equality columns first (
customer_id = ?,status = ?). Among themselves, their order does not matter much for this query. - Then the column you sort by, if the query has
ORDER BY. - Then the column with a range condition (
>,<,BETWEEN,LIKE 'abc%').
This is often called ESR: Equality, Sort, Range. The reason is the same as in the ArrayViz: a range condition gives you a run of entries in which the next column is no longer sorted, so any column after a range can only be filtered, never sought or used for ordering. A range column placed before the sort column forces a sort.
Here one query has all three parts: equality on customer_id, a range on total_cents and a sort on created_at. Compare three orders:
Press Run (⌘ Enter) to see what happens.(created_at, customer_id): no seek at all. The planner walks the whole index backwards in date order, checking each entry, and stops after five matches. That can be quick if matches are common and terrible if they are rare.(customer_id, total_cents, created_at): equality then range. It seeks on both, but the matching entries are sorted by total, not date, so it needsUSE TEMP B-TREE FOR ORDER BY: collect every match, sort, keep five.(customer_id, created_at, total_cents): equality, sort, range. It seeks oncustomer_id, reads that customer's entries newest first, checkstotal_centsfrom the index entry itself, and stops after five. No sort.
ESR is a starting point, not a law. If the range is very selective (total_cents > 39000 matches almost nothing) and the customer has a million orders, seeking on the range and sorting the few matches can win. That is a judgement you make with real data and EXPLAIN ANALYZE, covered in Reading EXPLAIN and EXPLAIN ANALYZE.
A common myth is "put the most selective column first". For a query with equality on both columns, the order barely changes the cost: the database descends to the same small run either way. What the order does decide is which other queries the index can serve. Put first the column that other queries also filter on alone, so one index covers several query shapes.
Indexes that remove the sort
ORDER BY ... LIMIT is where composite indexes shine. Without a matching index, the database must find every matching row, sort them all, and then throw most away. With one, it reads the first N entries in index order and stops. On a customer with 50,000 orders, that is the difference between sorting 50,000 rows and reading 20.
Press Run (⌘ Enter) to see what happens.The first query needs a sort because status sits between customer_id and created_at. Add status = 'paid' and the sort disappears, because now the dates inside the run are in order. The two-column index serves the first query with no sort. The last query mixes directions, status ascending and created_at descending, and the index is ascending on both, so SQLite sorts the right-hand part (USE TEMP B-TREE FOR RIGHT PART OF ORDER BY).
A B-tree can be read in either direction, so an index on (a, b) serves both ORDER BY a, b and ORDER BY a DESC, b DESC. It cannot serve ORDER BY a, b DESC. For that, declare the directions in the index:
CREATE INDEX orders_status_created_idx ON orders (status, created_at DESC);
-- Serves ORDER BY status, created_at DESC and, read backwards, ORDER BY status DESC, created_at.Postgres also lets you place NULLs (created_at DESC NULLS LAST); the index and the query must agree on that too. This pattern is also the base of keyset pagination, which Query Patterns That Scale builds on: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20 with an index on (created_at, id).
Skip scan: Postgres 18 bends the rule
Postgres 18 added B-tree skip scan. With an index on (status, created_at) and a query on created_at alone, Postgres 18 can treat the query as "for each distinct status, seek to this date", doing one small descent per status value instead of scanning everything. With four statuses, that is four quick descents. EXPLAIN ANALYZE in Postgres 18 shows the number of descents as Index Searches.
SQLite has had a similar skip-scan for years, but it only uses it once ANALYZE has told it the leading column has few distinct values:
Press Run (⌘ Enter) to see what happens.ANY(status) is the skip: one descent per distinct status. Skip scan rescues a query that slightly misses an index, and only when the skipped column has few distinct values. Skipping over 2,000 customers is 2,000 descents. It does not replace getting the order right, and advice written before Postgres 18 that says "the index is useless without the first column" is now slightly out of date for Postgres.
Covering indexes and index-only scans
In the plans above you may have seen USING COVERING INDEX. An index covers a query when it contains every column the query needs, so the database never visits the table. An ordinary index lookup costs an index descent plus one table fetch per matching row, and those fetches are usually the expensive part.
Press Run (⌘ Enter) to see what happens.Even fully in memory, skipping the table fetch roughly halves the time. On disk, where each fetch can be a random read, the gap is much larger.
SQLite and MySQL make an index covering by adding columns to the key. Postgres 11 and later also have INCLUDE, which stores extra columns in the leaf pages only, without making them part of the sorted key:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC)
INCLUDE (status, total_cents);
EXPLAIN (ANALYZE)
SELECT created_at, status, total_cents
FROM orders WHERE customer_id = 42
ORDER BY created_at DESC LIMIT 20;
-- Limit
-- -> Index Only Scan using orders_customer_created_idx on orders
-- Index Cond: (customer_id = 42)
-- Heap Fetches: 0INCLUDE columns cannot be used to seek or sort, but they also do not affect uniqueness, so CREATE UNIQUE INDEX ON users (email) INCLUDE (name) enforces unique emails while covering a login lookup.
There is a Postgres-specific catch. Because of MVCC, the index does not know whether a row version is visible to your transaction, so an Index Only Scan checks the table's visibility map, a small structure marking pages whose rows are all visible to everyone. For pages marked all-visible, it skips the heap. For the rest, it fetches the row anyway, counted as Heap Fetches. VACUUM is what sets those bits, so on a heavily updated table that autovacuum has not caught up with, an index-only scan degrades into an ordinary index scan. If you see high Heap Fetches, look at vacuum, not at the index.
Covering is a trade-off. Every extra column makes the index bigger and every update of that column becomes an index update (and in Postgres, no longer a HOT update). Cover the hot queries, not every query.
Partial indexes
A partial index has a WHERE clause and only contains the rows that match it. Two patterns cover most uses.
Queues and rare states. A jobs table has 50 million done rows and a few hundred pending ones. Workers only ever ask for pending jobs. CREATE INDEX jobs_pending_idx ON jobs (run_at) WHERE status = 'pending' is tiny, stays in memory, and is only updated when rows enter or leave the pending state.
Uniqueness for a subset. With soft deletes, an email must be unique among live accounts but may repeat among deleted ones. A partial unique index says exactly that. This one is also an expression index on lower(email):
Press Run (⌘ Enter) to see what happens.The plans show the two rules that catch people:
- The query must imply the index's
WHERE. Withoutdeleted_at IS NULL, the index might be missing matching rows (the deleted ones), so the planner cannot use it and scans. - The query must use the same expression.
email = ...is notlower(email) = .... The planner did use the partial index in the third query, but only as a smaller list of live rows to walk (SCAN ... USING INDEX), not to seek. In Postgres, the same applies: an index onlower(email)is used byWHERE lower(email) = lower($1), and only that.
Expression indexes in Postgres require the expression to be IMMUTABLE: lower(email) is fine, but anything depending on the time zone setting or now() is not. When you are tempted to index date(created_at) so that WHERE date(created_at) = '2025-06-01' is fast, the better fix is usually to rewrite the query as a range on the raw column, which a plain index serves.
Redundant and duplicate indexes
Because of the leftmost-prefix rule, an index on (a) is redundant next to one on (a, b): anything that can seek on (a) can seek on the composite. Dropping it saves writes and cache. There are real exceptions. Keep (a) if it is UNIQUE (the composite does not enforce that), if it is much smaller and serves a very hot query, or if its columns have a different sort direction. And (a, b) and (b, a) are not duplicates: they serve different queries.
Duplicates pile up in long-lived schemas: an ORM creates one index, a migration adds the same one under another name, and a UNIQUE constraint brings a third. Each costs on every write. Finding unused ones with Postgres's statistics views is part of Why the Database Ignored Your Index.
A workflow for designing an index
When a query is slow at work, do this before you write any CREATE INDEX:
- Get the real query, with its typical parameters and how often it runs. A query that runs 10,000 times a minute matters more than one that runs nightly.
- Write down its shape: equality columns, the sort, the range, and the columns it returns.
- Order the key columns: equality, then sort, then range. Consider
INCLUDEfor the returned columns if the query is very hot. - Check whether an existing index can be extended instead of adding a new one.
- Build it with
CREATE INDEX CONCURRENTLY, then confirm withEXPLAIN ANALYZEthat the plan uses it and that the time dropped. - Drop any index the new one makes redundant.
Check your understanding
(tenant_id, user_id, created_at). Which query can seek on two columns of it?SQLite 3.39. What do the two lines say?
from shopdb import connect
db = connect()
db.execute("CREATE INDEX orders_cust_status ON orders (customer_id, status)")
for where in ["status = 'paid' AND customer_id = 1", "status = 'paid'"]:
plan = db.execute("EXPLAIN QUERY PLAN SELECT id FROM orders WHERE " + where).fetchall()
print(plan[-1][3])Order the key columns of the best index for: WHERE tenant_id = ? AND status = ? AND created_at > ? ORDER BY priority DESC LIMIT 50
- Tap the steps below in the right order.
Match each need to the index feature that solves it.
Index Only Scan on a hot table, but with Heap Fetches: 48210 and no speed-up. What is the most likely cause?- composite index
- An index on several columns, sorted by the first, then by the second within equal firsts, and so on.
- leftmost-prefix rule
- A composite index on (a, b, c) can seek on a, on a and b, or on all three, but not on b or c alone.
- ESR
- A rule of thumb for column order: Equality columns, then the Sort column, then the Range column.
- skip scan
- Using a composite index without its leading column by doing one descent per distinct leading value. In Postgres since 18.
- covering index
- An index that contains every column a query needs, so the database never reads the table.
- visibility map
- A Postgres structure marking pages whose rows are visible to every transaction. Index-only scans skip the heap only for those pages.
- partial index
- An index with a WHERE clause that only contains matching rows. Queries must imply the same condition to use it.