A partial index is conditional: PostgreSQL can use it only when the query’s WHERE clause proves that every candidate row belongs to the index’s subset. Prepared statements can change whether that proof is available.
This implementation creates a transaction-scoped temporary orders table with many paid rows and a small pending subset. It creates a partial index ordered by order number but restricted to pending rows, then prepares one statement that filters by a status parameter and orders by order number.
The important decision is to compare that exact prepared statement under two session-local planning modes. First, force a custom plan; then force a generic plan. SET LOCAL plan_cache_mode keeps the experiment inside the transaction rather than changing a server-wide default. Run EXPLAIN EXECUTE before each execution and use the same pending parameter both times.
With custom planning, PostgreSQL has the concrete parameter value during planning. For the pending case, it can reason that the query satisfies the partial-index predicate, making that access path eligible. With generic planning, the plan must be valid for every future parameter value. It retains the parameter symbol rather than assuming it is pending, so the predicate is no longer provable and the partial index may not be eligible.
Both executions should still return the same status-filtered rows. A changed access path is not a changed query result; it is a consequence of different planning evidence.
There are limits. This fixture demonstrates planner reasoning, not a guaranteed plan or performance result on every PostgreSQL installation. Data distribution, query shape, statistics, and costs still influence the chosen plan. Forcing custom plans everywhere is not a universal fix either: generic plans can reduce planning work, especially when parameter values do not materially change the best access path.
Working example
const FIXTURE_STATUSES = new Set(['pending', 'paid', 'cancelled']);
function assertFixtureStatus(status) {
if (typeof status !== 'string' || !FIXTURE_STATUSES.has(status)) {
throw new RangeError(
`status must be one of: ${[...FIXTURE_STATUSES].join(', ')}`,
);
}
}
/**
* Builds a session-local PostgreSQL experiment specification.
*
* This builder describes expected partial-index eligibility; it does not run
* PostgreSQL or prove a particular server's chosen plan.
*/
export function buildOrdersExperiment({ status = 'pending' } = {}) {
assertFixtureStatus(status);
return {
sessionLocal: true,
preparedStatement: {
name: 'orders_by_status',
parameterType: 'text',
query: 'orders filtered by status and ordered by order_nr',
},
partialIndex: {
name: 'orders_pending_order_nr_idx',
key: 'order_nr',
predicate: "status = 'pending'",
},
runs: [
{
planCacheMode: 'force_custom_plan',
command: 'EXPLAIN EXECUTE',
status,
predicateProvenAtPlanning: status === 'pending',
},
{
planCacheMode: 'force_generic_plan',
command: 'EXPLAIN EXECUTE',
status,
// A generic plan must be valid for every possible $1 value.
predicateProvenAtPlanning: false,
},
],
proofBoundary:
'This script must be run against PostgreSQL. Its generated commands and these tests do not prove a live planner choice, a cache hit, or performance on any server.',
};
}
/** Returns a runnable PostgreSQL script for the supplied experiment. */
export function renderPostgresSql(experiment) {
if (!experiment || !Array.isArray(experiment.runs) || experiment.runs.length !== 2) {
throw new TypeError('experiment must be produced by buildOrdersExperiment');
}
const [customRun, genericRun] = experiment.runs;
assertFixtureStatus(customRun.status);
assertFixtureStatus(genericRun.status);
const literal = (value) => `'${value.replaceAll("'", "''")}'`;
const execute = (run) => `EXECUTE orders_by_status(${literal(run.status)});`;
const explain = (run) =>
`EXPLAIN (COSTS OFF) EXECUTE orders_by_status(${literal(run.status)});`;
return `BEGIN;
CREATE TEMP TABLE orders (
order_nr integer PRIMARY KEY,
status text NOT NULL,
total_cents integer NOT NULL
) ON COMMIT DROP;
-- Many non-pending rows make the pending subset representative.
INSERT INTO orders (order_nr, status, total_cents)
SELECT n, 'paid', 1000 FROM generate_series(1, 20000) AS n;
INSERT INTO orders (order_nr, status, total_cents) VALUES
(30001, 'pending', 2500),
(30002, 'pending', 1800),
(30003, 'pending', 4200),
(30004, 'cancelled', 900);
CREATE INDEX orders_pending_order_nr_idx
ON orders (order_nr)
WHERE status = 'pending';
ANALYZE orders;
PREPARE orders_by_status(text) AS
SELECT order_nr, status, total_cents
FROM orders
WHERE status = $1
ORDER BY order_nr;
SET LOCAL plan_cache_mode = ${customRun.planCacheMode};
${explain(customRun)}
-- Save this result set to compare with the generic execution below.
${execute(customRun)}
SET LOCAL plan_cache_mode = ${genericRun.planCacheMode};
${explain(genericRun)}
${execute(genericRun)}
DEALLOCATE orders_by_status;
COMMIT;`;
}
Read the full article: https://chriseugenerodriguez.com/blog/postgresql-partial-index-generic-plan
Top comments (0)