Sub topic 7
Writing queries the planner can match to the predicate
This chapter assumes you can write SELECT queries with WHERE and ORDER BY, and that you have already created a partial index. It builds on the earlier chapter on partial indexes. It covers why a correct partial index sometimes goes unused, and how to write queries that use it.
The rule: the query must imply the predicate
A partial index contains only the rows that satisfy its WHERE predicate. If the planner used it for a query that also needs other rows, the query would silently return incomplete results. So the planner uses a partial index only when it can prove that every row the query could return is also in the index.
In logical terms, the query's WHERE clause must imply the index predicate. The planner does not do general algebra for this proof. It uses a small set of rules, and you need to write queries that fit them.
The running schema is the orders and users tables from earlier chapters. This is the index we will test against:
CREATE INDEX orders_pending_created_idx
ON orders (created_at)
WHERE status = 'pending';Setting up an experiment
On a tiny table the planner may prefer a sequential scan whatever you do, so load enough rows that only about 1% are pending.
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 1000)::bigint + 1,
CASE WHEN g % 100 = 0 THEN 'pending' ELSE 'shipped' END,
(random() * 50000)::int,
now() - (g || ' minutes')::interval
FROM generate_series(1, 200000) AS g;
ANALYZE orders;Now run the query from the earlier chapter:
EXPLAIN
SELECT id, created_at
FROM orders
WHERE status = 'pending'
AND created_at < now() - interval '1 hour';You should see an index or bitmap scan on orders_pending_created_idx. The query contains status = 'pending', which is exactly the predicate. The created_at condition is then used as an ordinary index condition on the indexed column.
What the planner can and cannot prove
The planner recognizes a clause as implying the predicate in these cases:
- The clause is identical to the predicate, or one of the
ANDed conditions is. - Both compare the same expression to constants and the logic follows directly. For example, a predicate
total_cents > 10000is implied bytotal_cents > 20000but not bytotal_cents > 5000. - The predicate is
col IS NOT NULLand the query has a strict condition oncol, such ascol = 5. A strict condition is one that cannot be true whencolis null.
It does not try to reason beyond that. The table below uses the predicate status = 'pending'.
| Query condition | Uses the index? | Why |
|---|---|---|
| `status = 'pending'` | Yes | Identical to the predicate |
| `status = 'pending' AND created_at < now() - interval '1 hour'` | Yes | One `AND`ed term is the predicate |
| `status IN ('pending', 'paid')` | No | Allows rows the index does not contain |
| `status <> 'shipped'` | No | Matches statuses other than `pending` |
| `lower(status) = 'pending'` | No | Different expression, so no proof |
| Only `created_at < now() - interval '1 hour'` | No | Says nothing about `status` |
| `status = $1` in a generic plan | No | The value is unknown at planning time |
Rows that satisfy a condition but are not in the index are the reason for each "No". The planner rejects the index even when the data happens to contain only pending rows, because plans must be correct for any data.
Passing the proof makes the index a candidate. It does not guarantee the planner picks it. Cost estimates still decide, and the next chapter sections cover the common ways the proof fails.
Pitfall: parameters and generic plans
Prepared statements and many ORMs send status = $1 instead of a literal. PostgreSQL can plan such a statement two ways:
- A custom plan is built for the actual parameter values. It sees
status = 'pending'and can use the partial index. - A generic plan is built once without the values and reused. It sees only
status = $1, which does not implystatus = 'pending', so the partial index is excluded.
By default (plan_cache_mode = auto), PostgreSQL tries custom plans for the first few executions. It may then switch to a generic plan if that looks no more expensive than the custom plans. A query that used your index in testing can therefore stop using it in production after several calls. You can reproduce this in one session:
SET plan_cache_mode = force_generic_plan;
PREPARE pending_orders(text) AS
SELECT id, created_at
FROM orders
WHERE status = $1
AND created_at < now() - interval '1 hour';
EXPLAIN EXECUTE pending_orders('pending');The plan will not use orders_pending_created_idx. Switch to custom planning and compare:
SET plan_cache_mode = force_custom_plan;
EXPLAIN EXECUTE pending_orders('pending');Now the plan can use the partial index. Your options in application code are:
- Write the constant into the SQL text for queries meant to hit the partial index, for example
status = 'pending'. This is the simplest fix. It works because the predicate is fixed anyway. - Keep the parameter but add the predicate as a literal, for example
AND status = 'pending'in a query that takes other parameters. - Set
plan_cache_mode = force_custom_planfor that session or role. This costs planning time on every execution.
Pitfall: slightly different expressions
The comparison is structural. These queries mean the same thing to a person, but the planner cannot prove they match status = 'pending':
-- Different expression: a function wraps the column.
SELECT id FROM orders WHERE lower(status) = 'pending';
-- Disjunction: also allows rows outside the index.
SELECT id FROM orders WHERE status = 'pending' OR status = 'paid';Types matter too. If a predicate compares a column to a value of one type and the query forces a cast on the column, the expressions differ. Write the query with the same column and the same literal form as the predicate. The easiest check is to copy the predicate text into your query.
Matching with a unique partial index
The unique partial index from the earlier chapter has the same requirement in a less obvious place:
CREATE UNIQUE INDEX users_active_email_key
ON users (email)
WHERE deleted_at IS NULL;INSERT ... ON CONFLICT needs to infer which unique index to use as the arbiter. For a partial index, you must repeat the predicate in the conflict target:
INSERT INTO users (email)
VALUES ('[email protected]')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO NOTHING;Without the WHERE deleted_at IS NULL clause, PostgreSQL reports that there is no unique or exclusion constraint matching the ON CONFLICT specification. The same implication rule applies: the conflict target's predicate must be implied by the index predicate.
Lookups against active users also need the predicate to use the index for reads:
SELECT id
FROM users
WHERE email = '[email protected]'
AND deleted_at IS NULL;Without deleted_at IS NULL, this lookup cannot use users_active_email_key, because it must also consider soft-deleted rows.
Checking that the match works
Use EXPLAIN to confirm. If you expect a partial index and see a sequential scan, test whether the proof is the problem or the cost estimate is:
SET enable_seqscan = off;
EXPLAIN
SELECT id, created_at
FROM orders
WHERE lower(status) = 'pending';
RESET enable_seqscan;enable_seqscan = off does not forbid sequential scans. It adds a very large cost to them, so any usable index will win. If the partial index still does not appear, the planner could not prove the predicate, and you should fix the query. If it appears only with the setting off, the proof worked but the planner judged a sequential scan cheaper. In that case, check table statistics with ANALYZE and consider whether the index is worth keeping.
Common errors
- Writing the predicate as a parameter, such as
status = $1, and expecting the index to be used under a generic plan. - Using
IN,<>, orORwhere the predicate uses=. - Wrapping the column in a function in the query while the predicate uses the bare column.
- Omitting the predicate from
ON CONFLICTfor a unique partial index. - Testing on a tiny table, then concluding the index "doesn't work" because the planner chose a sequential scan.
Exercise
An index is defined as CREATE INDEX big_orders_idx ON orders (customer_id) WHERE total_cents > 10000;. Which of these queries can use it, and why? (a) WHERE customer_id = 7 AND total_cents > 20000; (b) WHERE customer_id = 7 AND total_cents > 5000; (c) WHERE customer_id = 7.
Show answer
Only (a) can use it. Its condition total_cents > 20000 implies total_cents > 10000, so every row it can return is in the index. Query (b) can return rows with total_cents between 5001 and 10000, which the index does not contain. Query (c) has no condition on total_cents, so it can return rows the index excludes.
Exercise
A prepared statement SELECT id FROM orders WHERE status = $1 AND created_at < $2 used orders_pending_created_idx for its first few executions, then became slow. What is the likely cause, and what is one fix?
Show answer
PostgreSQL switched from custom plans to a generic plan. In the generic plan status = $1 does not imply status = 'pending', so the partial index is excluded. One fix is to write the constant in the SQL text (status = 'pending'). Another is to set plan_cache_mode = force_custom_plan for that session or role.