Sub topic 6
Partial indexes: indexing only the rows you query
This chapter assumes you know how a B-tree index is searched and can read basic EXPLAIN output. It uses the orders and users tables from the schema at the start of this tutorial.
The idea
A normal index has one entry for every row in the table. Many queries only care about a small slice of those rows, such as orders still waiting to be processed, users who are not deleted, or jobs that have not run. A partial index is an index with a WHERE clause. PostgreSQL adds an entry only for rows that satisfy that condition, which is called the index predicate.
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';This index holds created_at values for pending orders and nothing else. An order with status shipped never appears in it.
Because the index is smaller, you get three benefits:
- Searches touch fewer pages, and more of the index stays in memory.
- Inserts and updates on rows outside the predicate do not have to modify the index.
- Less disk space is used, and there is less to vacuum and rebuild.
A worked comparison
The effect is easiest to see on a table where the interesting rows are rare. The script below loads 200,000 orders, of which one in 200 is pending. It then builds a full index and a partial index on the same column and compares their sizes.
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 1000)::bigint + 1,
CASE WHEN g % 200 = 0 THEN 'pending' ELSE 'shipped' END,
(random() * 50000)::int,
now() - g * interval '1 second'
FROM generate_series(1, 200000) AS g;
CREATE INDEX orders_created_idx ON orders (created_at);
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';
ANALYZE orders;
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname IN ('orders_created_idx', 'orders_pending_created_idx');The full index is usually a few megabytes. The partial index covers about 1,000 rows, so it is typically a few dozen kilobytes. Exact numbers depend on your version and settings, but the ratio should be close to the ratio of rows indexed.
Now run the query the partial index was built for:
EXPLAIN
SELECT id, created_at
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';You should see an Index Scan or Bitmap Index Scan on orders_pending_created_idx. The status = 'pending' test does not appear as an index condition. The index already guarantees it, so only the created_at comparison is applied inside the index.
If you drop the full index first, the planner has no choice. If both exist, the planner picks whichever it estimates to be cheaper, and that is usually the smaller one.
DROP INDEX orders_created_idx;When a partial index is a good fit
Partial indexes work best when two things are true. The queries you care about always filter on a condition that is stable and known in advance, and that condition selects a small fraction of the table.
Common patterns:
- Work queues. Rows move from
pendingtodone. Queries look for pending work, and the index stays tiny because finished rows leave it as they change status. - Soft deletes. Most queries add
deleted_at IS NULL. An index with that predicate ignores deleted rows. - Skewed values. If 98% of rows have
status = 'shipped'and you never search for them by that value, an index onstatusis mostly wasted. A partial index on the rare values is more useful. - Sparse columns. If a nullable column is mostly
NULL, an index withWHERE column IS NOT NULLindexes only the rows that have a value.
The indexed columns do not need to include the predicate column. This index serves queries for a customer's pending orders:
CREATE INDEX orders_customer_pending_idx
ON orders (customer_id)
WHERE status = 'pending';It stores customer_id for pending rows only. The predicate column status is not part of the key.
What a predicate can contain
The predicate is a boolean expression evaluated on a single row when that row is written. That sets some limits:
- It can reference columns of the table being indexed, constants, operators, and functions.
- It cannot contain a subquery or refer to other tables.
- It cannot use aggregate functions or window functions.
- Every function and operator in it must be immutable, meaning its result depends only on its arguments. A later chapter covers immutability in detail.
The last rule catches a common mistake. You might want an index of "recent" orders:
-- Fails: now() is not immutable, so the predicate is rejected.
-- CREATE INDEX orders_recent_idx ON orders (created_at)
-- WHERE created_at > now() - interval '1 day';Even if PostgreSQL accepted it, the rule would be meaningless. A row that was recent when inserted would be stale a day later, but the index entry would not change. A predicate has to describe a property of the row itself, such as its status, not the current time.
If you need a moving window, a fixed cutoff in the predicate (for example created_at > '2026-01-01') is allowed, but you have to rebuild the index to move it. In practice, a status column that changes when a row leaves the interesting set is the more maintainable approach.
The query must imply the predicate
A partial index is usable only when the planner can prove that every row the query could return is in the index. The planner does this by checking whether the query's WHERE clause logically implies the index predicate. The next chapter covers the matching rules in detail. For now, remember the simple case: if the query does not mention a condition that implies the predicate, the index is not considered.
-- Can use orders_pending_created_idx
SELECT id FROM orders
WHERE status = 'pending' AND created_at < now() - interval '1 hour';
-- Cannot: shipped orders are not in the index
SELECT id FROM orders
WHERE status = 'shipped' AND created_at < now() - interval '1 hour';
-- Cannot: the query does not restrict status at all
SELECT id FROM orders
WHERE created_at < now() - interval '1 hour';A query that omits the condition would return rows the index does not contain, so using it would give wrong answers. The planner never does that. It falls back to another index or a sequential scan.
Costs and trade-offs
A partial index is cheaper than the equivalent full index, but it is not free.
| Aspect | Full index | Partial index |
|---|---|---|
| Rows indexed | All rows | Only rows matching the predicate |
| Size | Grows with the table | Grows with the matching rows |
| Insert of a non-matching row | Adds an index entry | No index work |
| Queries it can serve | Any query using its columns | Only queries that imply the predicate |
| Risk | Wasted space on unused rows | Silently unused if a query drifts from the predicate |
The last row matters most in practice. A full index is forgiving. A partial index depends on every query using the exact condition it was designed around. If someone later changes the application to filter status IN ('pending', 'retrying'), the index no longer applies, and nothing raises an error. You will only notice a slow query.
Updates have a subtle effect. When a row's status changes from pending to shipped, the row stops matching the predicate. The old index entry points to a row version that is dead to the index's purpose, and vacuum later removes it. When a row changes from shipped to pending, a new entry is added. Also, columns mentioned in a predicate count as indexed columns when PostgreSQL decides whether an update can use the cheaper heap-only tuple (HOT) path. Frequent changes to the predicate column therefore cost more than changes to an unindexed column.
Choosing the predicate
A few guidelines help you pick a predicate that stays useful:
- Start from the query. Copy the stable filter conditions from the slow query's
WHEREclause, and index the columns used to search and sort. - Check the selectivity. Compare
count(*) FILTER (WHERE ...)withcount(*). A predicate that matches half the table saves little. - Prefer equality or
IS NULLtests on a column that is also the application's own definition of a state. These are easy to repeat exactly in every query. - Keep the predicate short. A long predicate is hard to match by hand and easy to get wrong in one of several queries.
- After creating the index, confirm with
EXPLAINthat the real query uses it, then checkpg_stat_user_indexes.idx_scanover time to confirm it continues to be used.
SELECT count(*) FILTER (WHERE status = 'pending') AS pending_rows,
count(*) AS all_rows
FROM orders;Exercises
Exercise
The table has 10 million rows, and 2% of them have deleted_at IS NOT NULL. Nearly all your queries on users filter WHERE deleted_at IS NULL and look up by email. Would a partial index ON users (email) WHERE deleted_at IS NULL be much smaller than a full index on email? Would it be a good choice if a quarter of your queries also look up deleted users by email?
Show answer
It would be only about 2% smaller, because 98% of rows match the predicate, so the size benefit is small. If a quarter of queries need deleted users too, the partial index cannot serve them, since those rows are not in it. A partial index pays off when the predicate excludes most rows and the queries consistently use the predicate. Here a full index, or a partial index chosen for another reason such as uniqueness, fits better.
Exercise
Why does CREATE INDEX ON orders (created_at) WHERE created_at > now() - interval '7 days' fail, and what is a better way to keep an index focused on rows that still need attention?
Show answer
The predicate calls now(), which is not immutable, so PostgreSQL rejects it. A predicate must describe a property of the row itself, because the index entry is decided once, when the row is written. A better approach is to index on a status column that changes when the row leaves the interesting set, for example CREATE INDEX ON orders (created_at) WHERE status = 'pending', and have queries include status = 'pending'.
Exercise
You built orders_pending_created_idx with predicate status = 'pending'. A query uses WHERE status = $1 AND created_at < $2 as a prepared statement and EXPLAIN shows a sequential scan. Give one likely cause and one fix.
Show answer
The statement is using a generic plan, in which $1 is unknown, so the planner cannot prove the query implies status = 'pending' and skips the partial index. Fix it by writing the literal into the query (status = 'pending') or by allowing custom plans, for example with SET plan_cache_mode = force_custom_plan.