Sub topic 13
Partial covering indexes
A partial covering index combines two ideas from earlier chapters. INCLUDE lets an index answer a query without visiting the heap. A WHERE clause on CREATE INDEX limits the index to the rows you actually query. Together they give you a small index that serves a hot query path with an index-only scan. This chapter assumes you know how INCLUDE, the visibility map and Heap Fetches work.
What a partial index is
A partial index is an index with a predicate. Only rows for which the predicate is true get index entries. Rows that fail it are skipped at insert time and never appear in the index.
Here is the example from the spine:
CREATE INDEX orders_new_customer_idx
ON orders (customer_id) INCLUDE (total)
WHERE status = 'new';This index has the following properties:
- The search key is
customer_id. - The payload column is
total. - Only rows with
status = 'new'are indexed.
In the data set from this tutorial, status is drawn from four values, and 'new' ends up on about one sixth of the one million rows. The partial index therefore holds roughly 170,000 entries instead of 1,000,000. You can check the saving directly:
CREATE INDEX orders_customer_total_full_idx
ON orders (customer_id) INCLUDE (total);
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS size
FROM pg_class
WHERE relname IN ('orders_customer_total_full_idx',
'orders_new_customer_idx');The partial index should be several times smaller. Exact sizes depend on your PostgreSQL version and fill factor. A smaller index means fewer pages to read, a better chance of staying in shared_buffers, and less work per write for rows outside the predicate.
When the planner can use it
The planner can use a partial index only if it can prove that the query's WHERE clause implies the index predicate. The proof is done at plan time, from the query text. It does not look at the data.
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total
FROM orders
WHERE status = 'new' AND customer_id = 42;This query contains status = 'new', which matches the predicate exactly, so the index is eligible. Without that condition, the index is not eligible, even if every row for customer 42 happens to be 'new':
-- Cannot use orders_new_customer_idx: nothing implies status = 'new'
SELECT customer_id, total FROM orders WHERE customer_id = 42;The planner's proof is simple. It handles identical conditions and some easy implications. For example, a predicate total > 100 is implied by a query condition total > 200. It does not do general theorem proving. Write the query condition to match the predicate as literally as you can.
Predicate columns need not be in the index
Notice that status appears in neither the key nor the INCLUDE list, yet the query filters on it. This still works as an index-only scan. When the index predicate already implies a query condition, the planner treats that condition as satisfied by the index. It does not need to read status from the entry. So the index only has to supply the columns the query outputs or filters on beyond the predicate: here, customer_id and total.
This is why partial covering indexes can be so compact. The column you filter by constantly (status) costs nothing in the index entries.
Constants and parameters
The implication proof needs a value known at plan time. The following two forms behave differently:
| Query form | Planner can prove `status = 'new'`? |
|---|---|
| `WHERE status = 'new'` (literal) | Yes |
| `WHERE status = $1` with a custom plan | Yes, the parameter value is substituted at plan time |
| `WHERE status = $1` with a generic plan | No, the value is unknown |
Prepared statements start with custom plans and may switch to a generic plan after several executions, depending on cost estimates and the plan_cache_mode setting. If your application sends status as a parameter and the partial index stops being used, a generic plan is the likely cause. Putting the literal 'new' in the query text avoids the problem.
The decision path
The following diagram shows the checks the planner effectively runs before it picks an index-only scan on a partial covering index.
The last step is the same as for any index-only scan. The visibility map still decides how many heap pages must be visited. A partial index does not change that.
Verifying the plan
After creating the index, run VACUUM (ANALYZE) orders so the visibility map and statistics are current. Then run the query:
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total
FROM orders
WHERE status = 'new' AND customer_id = 42;Look for these lines in the output:
Index Only Scan using orders_new_customer_idx on ordersIndex Cond: (customer_id = 42)Heap Fetches: 0, or a small number
The plan will not show Filter: (status = 'new') on the scan node, because the index predicate already guarantees it. If you see a Filter on status or a different index name, the planner used another path. Other indexes on customer_id can win on cost, especially when a result set is small. To test your index in isolation, you can drop the competing index inside a transaction and roll back:
BEGIN;
DROP INDEX orders_customer_total_full_idx;
DROP INDEX orders_customer_total_idx;
EXPLAIN SELECT customer_id, total
FROM orders
WHERE status = 'new' AND customer_id = 42;
ROLLBACK;DROP INDEX takes an ACCESS EXCLUSIVE lock on the table until the transaction ends, so run this only on a test system.
Write costs and HOT updates
A partial index saves write work for rows outside the predicate. An insert of a 'paid' row writes no entry into orders_new_customer_idx. A delete or vacuum of such a row has nothing to remove from it.
There are two caveats.
First, rows can move in and out of the predicate. If an application updates status from 'new' to 'paid', the old index entry becomes dead. If it updates a row into 'new', a new entry is inserted. In a workflow where every order starts as 'new' and leaves that state soon after, the partial index sees heavy churn. The index stays small, but each order produces an insert and a later dead entry that vacuum must clean.
Second, HOT (heap-only tuple) updates are decided per column, not per row. PostgreSQL allows a HOT update only if no indexed column changed. Columns used in an index predicate count as indexed. So these updates are not HOT, even for rows outside the predicate:
- Changing
status(a predicate column). - Changing
total(anINCLUDEcolumn). - Changing
customer_id(the key column).
If total is updated frequently, a covering index that includes it removes the HOT optimization from those updates. This costs more than the extra index size suggests. Check pg_stat_user_tables.n_tup_hot_upd against n_tup_upd before and after adding such an index.
When a partial covering index is a good fit
Use one when all of these hold:
- A query runs often, with a fixed condition on a low-cardinality or skewed column, such as
status = 'new',deleted_at IS NULLoris_active. - The matching rows are a minority of the table, so the index shrinks meaningfully.
- The output columns are few, stable and narrow.
- The table is vacuumed often enough to keep most pages all-visible.
Avoid it when the predicate matches most of the table (you save little), when the condition varies per query, or when the included columns change often.
Combining with UNIQUE
A partial index can also be unique, which enforces uniqueness only among the matching rows. A common pattern is one active record per owner:
CREATE UNIQUE INDEX orders_one_new_per_customer_idx
ON orders (customer_id) INCLUDE (total)
WHERE status = 'new';This rejects a second 'new' order for the same customer, while allowing any number of orders in other states. Uniqueness applies to customer_id only. total is payload, as in the earlier unique-index chapter. This is a business rule, so create it only if it is true for your data. It would fail on the sample table, which has many 'new' orders per customer.
Exercise
A query SELECT customer_id, total FROM orders WHERE status = $1 AND customer_id = 42 is run through a prepared statement with the parameter set to 'new'. After many executions, EXPLAIN shows that ordersnewcustomer_idx is no longer used. What is the most likely cause, and how can you fix it?
Show answer
The statement switched to a generic plan. With a generic plan the value of $1 is unknown at plan time, so the planner cannot prove that status = $1 implies the index predicate status = 'new'. Fix it by writing the literal 'new' in the query text, or by forcing custom plans with SET plancachemode = forcecustomplan.
Exercise
Why does the query WHERE status = 'new' AND customerid = 42 get an index-only scan on ordersnewcustomeridx even though status is neither a key column nor an INCLUDE column?
Show answer
The index predicate already implies the status condition, so the planner does not need to read status from the index entries. The index only has to supply customer_id (the key) and total (the INCLUDE column).