PostgreSQL / Intermediate: concurrency and maintainable SQL / Lesson 14
Partial indexes and predicate matching
Test a selective index against a workload without assuming that the planner must choose it.
On this page
Lesson goals
- Explain an index predicate and query implication.
- Inspect an illustrative plan and verify the result separately.
- Measure a partial index with representative data and write costs.
- Predict PostgreSQL partial-index membership and predicate implication.
- Evaluate partial uniqueness and cost-based plan selection with representative evidence.
Index a defined subset
A partial index contains entries only for rows satisfying its predicate. It can be useful when an application repeatedly searches a smaller subset, such as open tasks, but it adds maintenance and storage costs. The planner must be able to recognize that the query condition implies the predicate at planning time. Even when the index is eligible, a sequential scan may be cheaper for a small table or common value.
Create an isolated example
The following illustrative SQL is for a new disposable PostgreSQL 18 database. It creates three synthetic tasks and an index limited to open rows. It does not connect to a configured database or measure a production workload. In this fixture two rows satisfy the predicate; the completed task is outside the indexed subset.
CREATE TABLE lab_task (id integer PRIMARY KEY, status text NOT NULL, created_at timestamp NOT NULL);
INSERT INTO lab_task VALUES
(1, 'open', '2026-01-01 09:00:00'),
(2, 'done', '2026-01-01 10:00:00'),
(3, 'open', '2026-01-02 09:00:00');
CREATE INDEX lab_task_open_created_idx ON lab_task (created_at) WHERE status = 'open';
The index predicate is status = open and the indexed key is created_at. Its value depends on the actual workload and data distribution; this small fixture is for reasoning about membership, not performance.
Inspect eligibility and results
The next query explicitly includes the index predicate. EXPLAIN describes a chosen plan but does not promise that this index will be selected. Run the separate SELECT to inspect correctness; its ORDER BY includes a unique tie-breaker. A realistic evaluation needs enough representative data, current statistics, and equivalent query parameters. Do not infer production timing from a tiny fixture.
EXPLAIN SELECT id, created_at FROM lab_task
WHERE status = 'open' AND created_at >= '2026-01-01 00:00:00'
ORDER BY created_at, id;
SELECT id, created_at FROM lab_task
WHERE status = 'open' AND created_at >= '2026-01-01 00:00:00'
ORDER BY created_at, id;
The SELECT returns task ids 1 and 3 for the declared fixture. The planner may legitimately choose a sequential scan, and its plan text is environment-dependent. EXPLAIN without ANALYZE does not execute the SELECT.
Consider planning and parameters
Predicate matching is decided during planning, and PostgreSQL does not prove every mathematically equivalent expression. A generic parameterized predicate may not imply a fixed partial-index predicate for every possible parameter. Test the actual prepared-query and plan behavior in the deployed application rather than assuming a literal demonstration transfers unchanged. Maintain parameter binding for values; do not interpolate untrusted text to force a plan.
Measure the tradeoff
On an authorized representative dataset, record baseline latency, plan, returned rows, index size, and write workload. Test one index change and compare the same operations and data distribution. Include rows changing into and out of the predicate. Verify result equality and account for index creation and maintenance. An index that helps one query may be unnecessary or costly for the larger workload.
Define the indexed subset
A partial index contains entries only for rows satisfying its predicate. In the lesson’s fixture, tasks 1 and 3 have status open and task 2 is done, so an index WHERE status = open contains entries for 1 and 3, not 2. Define the predicate and intended query population first. A smaller index may reduce storage and maintenance for excluded rows, but it is not a general index for every status or every query.
A partial index is still maintained when changes affect indexed entries or move a row into or out of the predicate. Check the exact PostgreSQL version, table definition and workload before estimating benefit. The examples are PostgreSQL 18 synthetic SQL and reasoned plan decisions; no server or index operation was executed.
Prove predicate implication at planning
The planner can consider a partial index only when it can recognize that the query condition implies the index predicate. A literal query WHERE status = open directly matches an index predicate status = open, making the index a possible candidate. It does not force use: cost, statistics and table size can make a sequential scan cheaper, especially for a three-row fixture. A query for status = done cannot rely on an index containing only open rows to answer the complete result.
PostgreSQL does not use a general theorem prover for arbitrary equivalent expressions. Predicate form and planning-time knowledge matter. A parameterized predicate can prevent the planner from proving implication for every possible parameter value in a generic plan. Inspect the actual plan and plan mode for the target workload rather than assuming that a value supplied later always makes a partial index eligible.
Distinguish partial uniqueness from global uniqueness
A UNIQUE partial index enforces uniqueness only among rows satisfying its predicate. For example, UNIQUE on email WHERE active can prevent two active rows with the same email while allowing an inactive row outside the subset, subject to PostgreSQL’s NULL semantics and the exact definition. It does not establish a global unique email rule. Decide whether the business invariant is conditional and test rows entering and leaving the subset.
NULL and predicate truth matter: only rows for which the index predicate is true are indexed; false or unknown predicates do not satisfy it. If status is nullable, status = open does not include NULL. A uniqueness rule and a NOT NULL rule answer different questions. Verify actual constraints and the intended authorization scope; an index is not an access-control policy.
Measure the candidate and its tradeoffs
EXPLAIN shows a plan without executing the statement, while EXPLAIN ANALYZE executes it and reports runtime evidence. A partial index that is logically eligible can still be rejected by cost estimation. Compare representative open and done queries, parameter values, selectivity, table size and statistics. A three-row demonstration cannot prove production benefit. Record the exact index predicate and query text when interpreting a plan.
An index can improve one selective read while adding write maintenance and storage. Updates that change status can add or remove index entries. Measure insert, update and delete effects and overlap with existing indexes. Do not force a plan or disable sequential scans merely to make a partial index appear in a demonstration. Test in an isolated authorized PostgreSQL 18 environment.
Test implication, boundaries and changes
Build a fixture with open, done and NULL status, repeated keys and a transition from open to done. Predict index membership and query results independently: a query’s correctness cannot depend on the planner selecting a particular index. Test literal and parameterized predicates with the actual prepared-plan behavior and document why the planner can or cannot prove implication. Use final ORDER BY when output order matters.
Before an operational index change, define acceptance and recovery criteria, permissions and a representative workload. Compare exact result keys and independent counts, then measure the complete read and write cost. Preserve the original query’s semantics when rewriting a predicate to match an index. A plan node label alone does not prove a business result or a universal performance improvement.
20 worked examples
1. Indexed subset
Problem: Which fixture rows satisfy the partial-index predicate?
- Tasks one and three have status open.
- Task two has status done and fails the predicate.
-- tasks: (1,'open'),(2,'done'),(3,'open').
CREATE INDEX lab_open_idx ON lab_task(id) WHERE status='open';
Tasks 1 and 3
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: A partial index contains rows satisfying its predicate.
2. Literal candidate
Problem: Can the literal open query consider the index?
- The query condition directly matches the index predicate.
- The planner still compares estimated costs.
EXPLAIN SELECT id FROM lab_task WHERE status='open';
-- Index predicate: status='open'.
The partial index is a possible candidate, not a guaranteed choice.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Logical eligibility and cost-based selection are separate decisions.
3. Done query
Problem: Can an open-only index alone cover all done rows?
- A done row does not satisfy status=open.
- The query asks for the excluded status.
-- Index predicate: status='open'.
SELECT id FROM lab_task WHERE status='done';
No; done rows are outside the indexed subset.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: An incomplete subset cannot represent all requested done rows.
4. NULL status
Problem: Does a NULL status enter the open index?
- Comparing NULL with open yields unknown.
- A partial-index predicate includes rows for which it is true.
SELECT NULL::text='open' AS predicate;
NULL (unknown); the row is not in the open subset.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Unknown status is not silently treated as open.
5. Status transition in
Problem: What happens when a row changes from done to open?
- Its old status did not satisfy the predicate.
- Its new status satisfies status=open.
-- Task 2 initially has status=done.
UPDATE lab_task SET status='open' WHERE id=2;
Task 2 enters the logical indexed subset after the update.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Writes crossing the predicate boundary require index maintenance.
6. Status transition out
Problem: What happens when an open row becomes done?
- The old status satisfied the predicate.
- The new status does not satisfy it.
-- Task 1 initially has status=open.
UPDATE lab_task SET status='done' WHERE id=1;
Task 1 leaves the logical indexed subset.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: A partial index still has maintenance when membership changes.
7. Tiny table plan
Problem: Must the planner use the eligible index for three rows?
- The literal predicate can make the index eligible.
- The planner still compares costs for the small table.
-- Three-row fixture; query WHERE status='open'.
-- Open partial index exists.
No; a sequential scan may have lower estimated cost.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Logical eligibility does not force the planner to select this index over a cheaper scan.
8. Generic parameter
Problem: Why can a generic parameterized predicate prevent implication?
- The parameter can represent statuses beyond open.
- The partial index excludes those other rows.
PREPARE task_query(text) AS SELECT id FROM lab_task WHERE status=$1;
-- Generic plan must be valid for values other than open.
The generic plan may not prove the open-only predicate.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: The planner needs planning-time knowledge to prove the query implies the partial predicate.
9. Literal plus key
Problem: Can an additional key condition coexist with the predicate?
- The query requires open status.
- The id condition further narrows the requested row.
SELECT id FROM lab_task WHERE status='open' AND id=3;
-- Partial index predicate: status='open'.
The literal status condition makes the index a possible candidate.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Additional conditions do not remove the explicit predicate implication.
10. All rows query
Problem: Can the open-only index alone represent every task?
- The query requests all task statuses.
- The index predicate includes only open rows.
SELECT id FROM lab_task;
-- Fixture also contains a done task.
No; done rows are not in the partial index.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: The indexed subset is incomplete for the unrestricted population.
11. Partial unique conflict
Problem: What happens to duplicate active emails?
- Both the existing and candidate rows satisfy active.
- Their email values are equal in the stated fixture.
CREATE UNIQUE INDEX lab_active_email_uq ON lab_user(email) WHERE active;
-- Existing active email: a@example.test.
INSERT INTO lab_user(email,active) VALUES ('a@example.test',true);
The insert violates the partial unique index.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: The conditional uniqueness rule applies inside the indexed subset.
12. Inactive duplicate
Problem: Can an inactive duplicate lie outside that rule?
- The new row does not satisfy the active predicate.
- It therefore is outside the stated unique subset.
-- Existing active email: a@example.test.
-- Unique partial index: email WHERE active.
INSERT INTO lab_user(email,active) VALUES ('a@example.test',false);
The partial unique index alone does not reject this inactive row.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Partial uniqueness is not global uniqueness.
13. Entering unique subset
Problem: What if an inactive duplicate becomes active?
- The update moves B into the active subset.
- A already has the same indexed email there.
-- Active user A and inactive user B share an email.
-- Unique partial index: email WHERE active.
UPDATE lab_user SET active=true WHERE id='B';
The update violates the partial unique index.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Predicate transitions must satisfy the conditional uniqueness rule.
14. NULL predicate
Problem: Is a row with active NULL in WHERE active?
- The active value is NULL rather than true.
- The predicate WHERE active is not true for that row.
SELECT NULL::boolean IS TRUE AS in_subset;
false
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Partial-index membership requires its predicate to be true.
15. Nullable unique value
Problem: Does a unique partial index automatically require email?
- The index controls uniqueness in the selected subset.
- It does not declare the email column NOT NULL.
-- Index: UNIQUE (email) WHERE active.
-- email column is nullable; default NULL uniqueness semantics apply.
No; requiredness needs a separate rule.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Presence and conditional uniqueness are distinct constraints.
16. Predicate rewrite
Problem: Why must an equivalent-looking predicate be tested?
- Different expressions can differ on NULL or type semantics.
- The planner may not prove every equivalent formulation.
-- Index predicate: status='open'.
-- Query uses a more complex expression intended to mean open.
Verify both logical equivalence and planner implication.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: A readable match needs both correctness and planning evidence.
17. Explain without analyze
Problem: What does ordinary EXPLAIN provide here?
- EXPLAIN asks PostgreSQL for a plan.
- Without ANALYZE it does not collect actual runtime rows by execution.
EXPLAIN SELECT id FROM lab_task WHERE status='open';
A planned query without executing the SELECT.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Plan eligibility is an estimate-based decision.
18. Explain analyze
Problem: What does EXPLAIN ANALYZE do to the query?
- ANALYZE runs the supplied statement.
- The query can consume resources and wait.
EXPLAIN ANALYZE SELECT id FROM lab_task WHERE status='open';
It executes the SELECT and reports runtime information.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Collect actual evidence only in an authorized environment.
19. Write tradeoff
Problem: Why measure updates when adding an open-only index?
- The old row was inside the indexed subset.
- The new row is outside it.
-- Task status changes from open to done.
-- A partial index covers status='open'.
The update can require index entry maintenance.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: Read benefit must be weighed against write and storage costs.
20. Correctness independent of plan
Problem: Should query results change if the planner chooses a scan?
- The query predicate defines the result population.
- The planner chooses an access method for that population.
-- Query: status='open'.
-- Candidate plans: partial index scan or sequential scan.
No; both valid plans must return the same qualifying rows.
The fixture and plan decision are reasoned; PostgreSQL was not accessed.
Why this result follows: An index affects access, not the intended logical answer.
Common errors and fixes
The partial index is not used in the tiny lab.
- Why it happens
- The planner estimates a sequential scan is cheaper.
- How to fix it
- Measure the actual workload and inspect the plan rather than forcing an assumption.
- Prevent it next time
- Use representative data and current statistics in performance tests.
A prepared query misses the expected index.
- Why it happens
- Its planning context cannot prove the parameterized condition implies the fixed predicate.
- How to fix it
- Inspect the actual prepared plan and redesign the query or index when justified.
- Prevent it next time
- Test the same driver and parameter patterns used in deployment.
A report changes results after an optimization.
- Why it happens
- The query predicate was changed to resemble the index rather than preserve business semantics.
- How to fix it
- Restore the required filter and compare result sets.
- Prevent it next time
- Keep correctness tests alongside plan measurements.
20 practice exercises
1. Which rows are in the fixture index and why?
Show hint
Evaluate status=open for each fixture row.
Show worked solution
Tasks 1 and 3 satisfy status = open. Task 2 is done, so it does not satisfy the partial-index predicate.
Tasks 1 and 3 are open and satisfy the partial-index predicate; task 2 is done and is excluded. A NULL status would also fail to make the predicate true.
Check your solution
- Tasks 1 and 3 are in the subset.
- Task 2 is not in the subset.
2. Must PostgreSQL use the partial index for the shown SELECT?
Show hint
Separate eligibility from the planner’s cost choice.
Show worked solution
No. The literal predicate makes the index a possible candidate, but the planner can choose a sequential scan based on estimated cost, especially for three rows.
The literal open predicate can make the index a candidate, but PostgreSQL may choose a sequential scan based on estimated cost, particularly for a three-row table. Inspect the plan rather than assuming index use.
Check your solution
- The index is only a candidate.
- A sequential scan can be selected.
3. Tasks 1 and 3 are open and task 2 is done. Which rows enter an index WHERE status=open?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
Tasks 1 and 3 satisfy the predicate; task 2 does not. The index contains only the selected subset, so it is not a complete index for all task statuses.
Check your solution
- Tasks 1 and 3 enter
- Task 2 is excluded
4. A literal query uses WHERE status=open and a matching partial index exists. Must PostgreSQL use it?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. The literal predicate can make the index eligible, but the planner can choose a sequential scan when its estimated cost is lower, particularly for a tiny table.
Check your solution
- The index is a candidate
- A sequential scan can be chosen
5. Does an open-only partial index contain a task whose status is NULL?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. status=open evaluates to unknown for NULL, and the predicate must be true for membership. Decide separately whether NULL status is permitted in the schema.
Check your solution
- NULL does not satisfy open
- Define nullability separately
6. A task changes from done to open. What happens to its partial-index membership?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
It enters the logical indexed subset because the new row satisfies the predicate. The update can require index maintenance even though the index excludes done rows.
Check your solution
- New status satisfies the predicate
- Update has index-maintenance work
7. A task changes from open to done. What happens to its partial-index membership?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
It leaves the logical indexed subset because the new status no longer satisfies the predicate. Test the write and workload impact instead of treating the index as maintenance-free.
Check your solution
- New status is excluded
- The transition requires maintenance
8. Can an index WHERE status=open alone represent all rows for an unrestricted task query?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. The query includes done and potentially NULL rows that the index predicate excludes. The planner needs a complete access strategy for the requested population.
Check your solution
- The query requests all statuses
- The partial subset omits some rows
9. Why might a generic prepared plan with status=$1 not use an open-only partial index?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
The generic plan must work for parameter values other than open, so it may not prove that the query implies the fixed partial predicate. Inspect the actual prepared-plan behavior and target version.
Check your solution
- Parameter can take other values
- Implication may not be provable
10. A query has status=open AND id=3. Can an index WHERE status=open be considered?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
Yes, the explicit status condition implies the partial predicate and the id condition further narrows the result. The planner still decides by estimated cost whether to use the index.
Check your solution
- Predicate implication holds
- Selection remains cost-based
11. A UNIQUE partial index covers email WHERE active. What happens to two active equal emails?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
The second active row conflicts with the conditional unique rule, assuming the stated values compare equal and no special NULL case applies. Both rows lie inside the indexed subset.
Check your solution
- Both rows are active
- Duplicate indexed email is rejected
12. Can an inactive row share an email with an active row under only that partial unique rule?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
Yes, the inactive row is outside the active subset, so that partial index alone does not reject it. Check any other unique constraints and the business rule separately.
Check your solution
- Inactive row is outside the subset
- Partial uniqueness is not global
13. An inactive duplicate email becomes active while another matching active row exists. What happens?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
The update moves the row into the unique subset and conflicts with the existing active email. Resolve the business conflict rather than assuming the earlier inactive insert guaranteed activation.
Check your solution
- The row enters the subset
- The duplicate active email conflicts
14. Does UNIQUE (email) WHERE active require email to be non-null?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. The partial unique index controls uniqueness in its subset but does not declare the column NOT NULL. Define requiredness and the intended PostgreSQL NULL uniqueness policy separately.
Check your solution
- Uniqueness is conditional
- Requiredness needs a separate rule
15. A query expression is intended to mean status=open but is complex. Why inspect its plan?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
The expression may differ on NULL or type semantics, and PostgreSQL may not prove every mathematical equivalence to the index predicate. Verify result correctness and actual planning evidence.
Check your solution
- Check logical equivalence
- Check planner implication
16. Does ordinary EXPLAIN execute a SELECT to obtain actual rows?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. It reports a planned query and estimates without executing the SELECT for runtime evidence. EXPLAIN ANALYZE executes the statement and must be used in an authorized environment.
Check your solution
- EXPLAIN is planned evidence
- ANALYZE executes the statement
17. Why can an eligible partial index still be ignored by the planner?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
The planner may estimate that a sequential scan or another access path costs less for the table and parameter distribution. Eligibility proves only a possible path, not the cheapest one.
Check your solution
- Eligibility is not selection
- Compare estimated costs
18. An open-only index improves one lookup. What write cost should be tested?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
Measure inserts and updates that enter, leave or change the indexed subset, along with storage and overlapping indexes. A selective read gain does not establish a benefit for the whole workload.
Check your solution
- Test membership-transition writes
- Measure storage and maintenance
19. Should query results change when PostgreSQL selects a sequential scan instead of the partial index?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
No. Valid plans must satisfy the same query predicate and return the same logical qualifying rows. An index changes access strategy, not the business result.
Check your solution
- Qualifying rows remain the same
- Only access strategy changes
20. What evidence supports accepting a partial index for a real workload?
Show hint
Trace predicate truth, planning-time implication and the complete workload.
Show worked solution
Verify exact result keys and predicate implication, then compare representative read plans and write costs with the actual PostgreSQL version and settings. Record thresholds and a recovery plan for any authorized change.
Check your solution
- Verify result and implication
- Measure read and write tradeoffs
Key takeaways
- A partial index covers only rows meeting its predicate.
- Eligibility requires planner-recognizable implication; selection remains cost based.
- Measure the actual workload and preserve query semantics.
- A partial index includes only rows satisfying its predicate.
- A matching predicate makes an index eligible, not mandatory.
- Partial uniqueness applies only within the indexed subset.