Code review: why a generic prepared plan cannot trust a partial index

Code review: why a generic prepared plan cannot trust a partial index

●3 ●55
calendar_today ago • schedule3 min read
— Originally published at chriseugenerodriguez.com

Review the failure condition first

The key assertion is not that a partial index always wins. It is that a concrete pending value can establish the partial-index predicate during custom planning, while a generic plan cannot establish that predicate from an unknown parameter. A non-pending concrete value also fails the proof, which confirms that the test is modeling eligibility rather than claiming every custom plan uses the index.

Prerequisites

Use PostgreSQL, permission to create temporary tables in a session, and a client that can run one transaction containing PREPARE, SET LOCAL, EXPLAIN EXECUTE, and EXECUTE. The generated script is an experiment description and runnable fixture; its recording-style checks do not reproduce a live PostgreSQL planner decision.

Implementation decision

Keep the setup deliberately narrow. Create a temporary orders table, load mostly paid rows with a small pending subset, and define an index on the ordering column only for rows whose status is pending. Prepare one query with a status parameter.

Then run the same prepared statement twice in the same transaction. Force a custom plan for the first inspection and a generic plan for the second. SET LOCAL is the important containment choice: it limits the comparison to the current transaction and avoids turning a diagnostic exercise into a persistent configuration change.

Expected result

For a custom execution using pending, EXPLAIN EXECUTE has a concrete value available to planning. PostgreSQL can therefore prove the query lies within the index predicate, so the partial index is eligible. Under a generic plan, the planner must preserve correctness for any value of the parameter. It sees a placeholder, cannot assume pending, and may choose an access path that does not use the partial index. The returned rows remain the same.

Limitation

Eligibility is not a promise of an index scan. PostgreSQL still weighs costs, statistics, and the surrounding query shape. Likewise, forcing custom planning globally may trade lower execution cost for more planning work. Use this fixture to diagnose the proof boundary, then evaluate the real workload before changing plan-cache behavior or index design.

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

Want more #architecture deep dives?

Join 6,128+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

0 votes

More Posts

The Sovereign Vault — A Comprehensive Guide to Protocol-Driven AI

Ken W. Algerverified - Jun 4

Short links that outlive the vendor: a newsroom URL shortener on WordPress and AWS

jaafarabazid - Nov 10

Don’t Over-Engineer: Why the Best Code is Code You Didn’t Write (YAGNI)

Mohamed Ahmed - Oct 3

Screaming Frog Review (2026): The Technical SEO Crawler I Audit With | FloxoLab

floxolab - Oct 21

SE Ranking Review (2026): Pros, Cons, and Verdict

floxolab - Oct 22
chevron_left
1.2k Points • 58 Badges
Santa Monica, CA • chriseugenerodriguez.com
44Posts
0Comments
11Connections
10 years fe

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!