Skip to content
R.

Why a PostgreSQL partial index vanishes in generic plans

Use a session-local prepared statement to show why a partial index is visible to a custom plan but can disappear from a generic plan.

About 16 min readComments

A partial index can disappear from a prepared query without any change to the table, the predicate, or the returned rows. The missing piece is the planning mode. PostgreSQL can either tailor a prepared statement to a specific parameter value or keep one generic plan that must remain valid for every future execution. Those are different contracts, and a partial index depends on the stricter one.

This article uses one session-local fixture to make that boundary visible. It builds a skewed orders table, creates a partial index for pending rows, prepares one status-filtered query, and compares EXPLAIN EXECUTE under force_custom_plan and force_generic_plan. The goal is not to prove a performance number. The goal is to show why a concrete pending value can justify the partial index while a generic plan cannot assume that same value.

The same query can lose the index when the plan changes

A partial index can look straightforward until a prepared statement enters the picture. In the fixture for this article, the table contains mostly paid orders and only a small pending subset. The index covers just the pending rows, so a query with a concrete pending value has enough information to justify that index during planning.

The confusing part appears when the exact same prepared query is forced through a generic plan. The SQL text has not changed, the rows have not changed, and the result set is still the pending subset. Yet the planner no longer has permission to assume that the parameter will be pending every time, so the predicate proof disappears.

That difference is not a bug in the index and not a contradiction in PostgreSQL's behavior. It is the consequence of asking the planner to produce one plan that must remain valid for every possible parameter value. The article keeps that distinction visible so the missing index scan is understandable instead of mysterious.

The useful question is not whether the query text mentions the same status literal in both executions. The useful question is whether the planner can rely on that literal at planning time. A custom plan can; a generic plan cannot. Once that ownership boundary is clear, the rest of the behavior follows naturally.

main.mjs / javascript
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;`;
}

SourcesPostgreSQL: Partial Indexes (opens a new tab)PostgreSQL: PREPARE (opens a new tab)

Keep the experiment session-local and force the two plan modes

The fixture does not ask you to change any server default. It begins with a transaction, creates a temporary orders table, loads a representative skew, defines the partial index, prepares one statement, and then flips plan_cache_mode locally with SET LOCAL. That keeps the scope narrow and makes the experiment safe to repeat inside one session.

Using SET LOCAL matters because it limits the setting to the current transaction. That means the comparison is about planner choice, not about altering the server's long-term behavior. The point is to isolate one decision surface and compare the same prepared statement under two planning modes, not to reconfigure PostgreSQL in a way that could affect other sessions.

The query itself is simple on purpose: select order_nr, status, and total_cents from orders where status = $1 order by order_nr. The partial index is on order_nr with a predicate of status = 'pending'. That arrangement lets the article demonstrate the planner's predicate reasoning without hiding it behind joins, functions, or unrelated filters.

A small, controlled table is more useful here than a large, realistic schema because the point of the article is proof, not benchmark theater. The prepared statement is valid either way, the rows are the same either way, and only the planning assumptions differ. That is the exact boundary the reader needs to see.

SourcesPostgreSQL: PREPARE (opens a new tab)

A partial index is only usable when the predicate is provable

PostgreSQL's partial-index rule is stricter than many people expect. The planner does not try to prove arbitrary logical equivalence; it checks whether the query's WHERE clause implies the index predicate strongly enough to trust the index. For simple cases, that can mean a literal match or an implication the planner understands directly. For anything more abstract, the index may remain invisible.

That limitation is exactly what makes partial indexes predictable enough to be useful. If the planner attempted open-ended theorem proving, planning would become both slower and less reliable. Instead, PostgreSQL uses a deliberately limited recognition model. The article's query is designed to sit right on that boundary: the custom plan can see the concrete pending value, but the generic plan must stay agnostic.

The index in the fixture also illustrates that the indexed column and the predicate column do not need to be the same. The key is not a perfect column match; the key is that the query must imply the predicate. In the experiment, the index key is order_nr, while the predicate is status = 'pending'. The planner still needs the predicate proof before it can treat the index as usable.

That is why the article keeps repeating the word prove rather than merely match. A partial index is not an index that magically appears whenever the table is smaller. It is an index that exists only for a subset of rows, so the planner must be able to prove the query stays inside that subset. If it cannot, the index is not a safe choice.

SourcesPostgreSQL: Partial Indexes (opens a new tab)

Custom plans know the value; generic plans only know the placeholder

Prepared statements are not one thing. PostgreSQL can execute them with a custom plan that uses the actual parameter values supplied to EXECUTE, or with a generic plan that stays the same across executions. That split is what makes prepared statements a performance feature, but it is also what creates the partial-index surprise.

In the article's command sequence, EXPLAIN EXECUTE makes the difference visible. A custom plan for the pending case can show the planner a literal pending value, which means the predicate can be evaluated against the partial index definition during planning. A generic plan, by contrast, must continue to represent the parameter as a symbol.

The planner's caution is reasonable. If a generic plan had to promise a partial index based on one observed value, it could become invalid for another execution in the same session. PostgreSQL avoids that trap by refusing to assume the parameter will always satisfy the predicate. The result is a legal plan that may be broader, even if it is less selective.

This is why the article compares the two modes explicitly instead of hand-waving about prepared statements in general. The question is not whether prepared statements are slower or faster. The question is whether the planning mode changes the planner's ability to prove the partial-index predicate from the available evidence.

SourcesPostgreSQL: PREPARE (opens a new tab)

EXPLAIN EXECUTE shows the evidence the planner had

The documentation for PREPARE calls out EXPLAIN EXECUTE for exactly this reason. When a generic plan is in use, the plan text contains parameter symbols such as $1. When a custom plan is in use, the supplied value appears concretely in the plan. That visual difference is more than cosmetic: it tells you what information was available to the planner.

The article uses that signal as a diagnostic boundary. If the plan still contains $1, the planner did not get to reason from a specific status value. If the plan shows a concrete pending literal, the planner had the information needed to prove that the query stayed inside the partial-index predicate. The index's appearance or disappearance is then a consequence of that evidence, not a mystery artifact.

This also helps separate planning from execution. The query can still return the same rows even when the plan shape changes. That is crucial, because a valid plan is not the same as the most efficient plan. The article's paired EXECUTE statements verify result equality so readers do not confuse a change in access path with a change in semantics.

That distinction becomes important when a missing partial index is investigated in production. Seeing a sequential scan or a different index scan does not automatically mean the query is wrong. It may simply mean the planner no longer has a concrete value it can trust at planning time. EXPLAIN EXECUTE is the tool that surfaces that difference cleanly.

SourcesPostgreSQL: PREPARE (opens a new tab)PostgreSQL: Partial Indexes (opens a new tab)

The result set stays the same even when the access path changes

A useful experiment needs a semantic check as well as a planning check. The fixture therefore executes the prepared statement after each EXPLAIN EXECUTE and compares the same status-filtered rows in both modes. That protects the article from accidentally implying that a different plan means a different answer. It does not.

The table contents make that comparison easy to reason about. Most rows are paid, a few are pending, and the partial index only covers the pending subset. The query uses the same prepared statement name, the same parameter type, and the same status value in both plan modes. The only thing that changes is whether PostgreSQL is allowed to tailor the plan to that concrete value.

The result equality matters because it shows what the planner owns and what the application owns. PostgreSQL owns the access path. The application owns the semantics of which rows qualify. If the same pending rows come back from both executions, then the index disappearance is about plan admissibility, not about correctness.

That boundary is also why the article avoids overclaiming performance. A custom plan may use the partial index and a generic plan may not, but the article does not infer a universal timing rule from that fact. The useful lesson is narrower: if a prepared statement falls back to a generic plan, the planner may lose the proof needed for a partial index even though the rows returned remain identical.

SourcesPostgreSQL: PREPARE (opens a new tab)

An incomplete fix is to blame the index instead of the plan

One tempting explanation is that the partial index is somehow unreliable or that PostgreSQL is ignoring a useful optimization. That interpretation misses the key detail: a partial index is conditional by design. If the planner cannot prove the condition for all possible values of the prepared parameter, it is behaving conservatively, not incorrectly.

Another incomplete repair is to force every prepared statement to stay custom forever. That would make the specific experiment easier to read, but it would also erase the real tradeoff the documentation describes. Generic plans exist to save planning time. For some workloads that is a win, and for others it is a poor fit. The article preserves that choice instead of pretending one mode is always superior.

A different dead end is to rewrite the query until it happens to resemble the predicate more closely, even when the semantic shape is not really clearer. PostgreSQL can only recognize simple implications; cosmetic rewrites are not a substitute for a planner that knows the real value. If the query still depends on a parameter, the generic plan still cannot assume the parameter's value.

The right fix depends on the workload, not on the article alone. If the application often executes the same prepared statement with pending values, custom planning may be enough. If the mix of values is broad, the generic plan may be the reasonable default even though the partial index disappears. The article leaves that decision to the reader's actual access pattern.

SourcesPostgreSQL: Partial Indexes (opens a new tab)

Know the limits before you reach for a partial index

Partial indexes are best when the subset is stable and worth naming explicitly. The documentation warns that they work best when the common values are predetermined and not in constant flux. That caution matters here too: if the notion of pending versus not pending changes frequently, the partial index may need maintenance, and the planning advantage may not justify the operational cost.

Prepared statements add another limit. The article only shows one session-local comparison with one status value and one predicate. That is enough to explain the planner behavior, but it is not enough to claim that every workload with prepared statements will behave the same way. A different data distribution, a different predicate, or a different query shape can produce a different plan choice.

The pattern also stops helping when the real need is broader than one subset. If the query needs many status values equally often, a partial index on pending rows may be too narrow to matter. In that case a different index design, or no partial index at all, may be the better choice. The article's value is in clarifying the tradeoff, not in recommending partial indexes universally.

The most useful takeaway is a decision rule: if a concrete value proves the partial-index predicate, a custom plan can use that proof; if the statement is planned generically, PostgreSQL must assume the parameter might be something else. Once that is visible, the missing index scan becomes an expected consequence of planning rules rather than a planner mystery.

main.test.mjs / javascript
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildOrdersExperiment, renderPostgresSql } from './main.mjs';

test('pending status has a custom-plan proof but not a generic-plan proof', () => {
  const experiment = buildOrdersExperiment({ status: 'pending' });

  assert.equal(experiment.sessionLocal, true);
  assert.equal(experiment.preparedStatement.name, 'orders_by_status');
  assert.deepEqual(experiment.runs, [
    {
      planCacheMode: 'force_custom_plan',
      command: 'EXPLAIN EXECUTE',
      status: 'pending',
      predicateProvenAtPlanning: true,
    },
    {
      planCacheMode: 'force_generic_plan',
      command: 'EXPLAIN EXECUTE',
      status: 'pending',
      predicateProvenAtPlanning: false,
    },
  ]);
});

test('a concrete non-pending status does not imply the pending partial-index predicate', () => {
  const experiment = buildOrdersExperiment({ status: 'paid' });

  assert.equal(experiment.runs[0].planCacheMode, 'force_custom_plan');
  assert.equal(experiment.runs[0].status, 'paid');
  assert.equal(experiment.runs[0].predicateProvenAtPlanning, false);
  assert.equal(experiment.runs[1].predicateProvenAtPlanning, false);
});

test('omitting status uses the pending fixture boundary case', () => {
  const experiment = buildOrdersExperiment();
  const sql = renderPostgresSql(experiment);

  assert.equal(experiment.runs[0].status, 'pending');
  assert.equal(experiment.runs[1].status, 'pending');
  assert.equal(typeof sql, 'string');
  assert.ok(sql.length > 0);
});

test('unsupported fixture statuses are rejected instead of becoming SQL input', () => {
  assert.throws(
    () => buildOrdersExperiment({ status: "pending'; DROP TABLE orders; --" }),
    {
      name: 'RangeError',
      message: 'status must be one of: pending, paid, cancelled',
    },
  );
});

SourcesPostgreSQL: PREPARE (opens a new tab)PostgreSQL: Partial Indexes (opens a new tab)

Share LinkedIn Email Subscribe

Discussion

Leave a comment

Comments appear after review. No email needed.

Image preview

Follow the blog

Choose email updates or your favorite RSS reader.

The weekly email

New articles on code, design, and AI. Fridays, only when there is something new.

By subscribing, you agree to weekly blog emails.
Confirm in your inbox. Unsubscribe anytime. Privacy

Use OpenRSS

Preview the feed, then choose a reader to subscribe.

Open in OpenRSS (opens a new tab)

Already have a reader?

Paste this link into your reader's Add feed option.

Prefer a reader? RSS does not require an email address. View XML feed