Skip to content
R.

Read pg_index after a concurrent index build

Read pg_index after CREATE INDEX CONCURRENTLY to distinguish a leftover invalid index from one PostgreSQL can use for queries.

About 15 min readComments

A concurrent PostgreSQL index build can leave you with a name that looks normal and a catalog row that is anything but. The hard part is not finding the index. The hard part is deciding whether PostgreSQL considers it safe for queries, still maintained by writes, or simply an invalid remnant from a failed build.

This article reads the answer from pg_index itself instead of from a loose description of the index name. The useful distinction is between an index that exists, an index that is live, an index that is ready for inserts, and an index that is actually query-usable. Those are related states, but they are not the same state.

What the catalog rows are actually for

A concurrent index build creates a confusing in-between state on purpose. PostgreSQL enters the new index in the catalogs first, then performs the table scans, and only later marks the index valid when the build has finished successfully. That means the object can exist before the database is willing to trust it for query planning.

The practical problem is that a name in pg_index does not automatically mean the index is safe to use. The catalog row is the evidence, but the booleans in that row decide whether the index is merely present, ready for writes, actually visible to queries, or still waiting for old snapshots to age out.

That distinction matters after a failure and also after a successful build. The documentation for CREATE INDEX CONCURRENTLY says a problem during the scans can leave behind an invalid index that is ignored for querying but still imposes update overhead. The same page also warns that even a completed concurrent build may not be immediately usable by every query if older transactions still exist.

So the question is not whether the index exists. The question is which catalog flags say it is a leftover artifact, which say it is maintained by writes, and which say PostgreSQL will consider it for query plans. That is the contract this article reads directly from the system catalogs.

main.mjs / javascript
export function indexCatalogQuery(indexName) {
  if (typeof indexName !== 'string' || indexName.trim() === '') {
    throw new TypeError('indexName must be a non-empty string');
  }

  return {
    text: `
      SELECT
        index_class.relname AS index_name,
        table_class.relname AS table_name,
        index_data.indisvalid,
        index_data.indisready,
        index_data.indislive,
        index_data.indcheckxmin
      FROM pg_index AS index_data
      JOIN pg_class AS index_class ON index_class.oid = index_data.indexrelid
      JOIN pg_class AS table_class ON table_class.oid = index_data.indrelid
      WHERE index_data.indexrelid = $1::regclass
    `,
    values: [indexName],
  };
}

const BOOLEAN_FIELDS = [
  'indisvalid',
  'indisready',
  'indislive',
  'indcheckxmin',
];

export function inspectPgIndexRow(row) {
  if (row === null || typeof row !== 'object' || Array.isArray(row)) {
    throw new TypeError('pg_index row must be an object');
  }

  for (const field of BOOLEAN_FIELDS) {
    if (typeof row[field] !== 'boolean') {
      throw new TypeError(`pg_index row field ${field} must be boolean`);
    }
  }

  const readyForInserts = row.indisready && row.indislive;
  const readyForQueries = row.indisvalid && row.indislive && !row.indcheckxmin;

  let state;
  if (!row.indislive) {
    state = 'being-dropped';
  } else if (!row.indisvalid) {
    state = 'invalid-leftover';
  } else if (row.indcheckxmin) {
    state = 'valid-but-waiting-for-old-snapshots';
  } else {
    state = 'query-usable';
  }

  return {
    indexName: row.index_name ?? null,
    tableName: row.table_name ?? null,
    state,
    readyForInserts,
    readyForQueries,
    // An invalid concurrent-build artifact can still be maintained by writes.
    failedConcurrentBuildLeftover: row.indislive && !row.indisvalid,
  };
}

SourcesPostgreSQL: CREATE INDEX (opens a new tab)PostgreSQL: pg_index (opens a new tab)

How a concurrent build fails and leaves a remnant

The failure mode to keep in mind is not a silent half-finished file on disk. PostgreSQL tells you the build failed and leaves an invalid index behind when something goes wrong during the scans, such as a deadlock or a uniqueness violation for a unique index. The documentation is explicit that this index is incomplete and should be dropped and rebuilt, or in some cases rebuilt with REINDEX INDEX CONCURRENTLY.

That is why the catalog row must be read as a diagnostic artifact instead of a success signal. An invalid leftover can still be maintained by INSERT and UPDATE activity, so it can continue to cost work even though it is not safe for query planning. In other words, the database has not forgotten it; it has only refused to trust it.

The article’s implementation models that distinction with a state called invalid-leftover. That is a useful label because it encodes the two facts a reader needs at the same time: the build did not complete successfully, and the object may still participate in write overhead. The problem is not merely that the index is broken; it is that the broken object remains operational enough to matter.

That is also the point where a simple existence check fails. Listing indexes by name cannot tell you whether you should drop, rebuild, or ignore one for query diagnosis. Only the catalog flags show whether the index is still live, whether it is valid for queries, and whether it is being phased out.

SourcesPostgreSQL: CREATE INDEX (opens a new tab)

Read indisvalid first when you ask about queries

The most important flag for the question in the title is indisvalid. PostgreSQL defines it as the indicator that the index is currently valid for queries. If it is false, the index is possibly incomplete and must not be used for querying. That is the clearest separation between a catalog row that exists and a catalog row the planner may trust.

The implementation mirrors that meaning directly. A row with indisvalid = false becomes the invalid-leftover state, and the helper marks readyForQueries as false. That is the correct conservative behavior because the catalog promises the index might be incomplete. Even if the row is still being maintained by writes, it cannot safely answer reads.

This is the first check a human should perform as well. If the flag is false, the index is not query-ready, regardless of whether it has a familiar name or appears under the table in a \d listing. The pg_index row is more precise than a descriptive listing because it exposes the actual booleans rather than a summarized label.

That precision matters because query readiness is not the same as object existence. A leftover invalid index may be present, may still be receiving maintenance, and may still consume storage and write time, but none of that makes it safe for planning. The right reading starts with indisvalid and only then asks what other state the row is in.

SourcesPostgreSQL: pg_index (opens a new tab)

Why indisready is not the same as query-usable

The second flag that tends to confuse readers is indisready. PostgreSQL describes it as the indicator that the index is currently ready for inserts. False means INSERT and UPDATE operations must ignore it. True means writes should maintain it. That is a maintenance contract, not a query-planning contract.

That difference is why the article’s implementation keeps readyForInserts and readyForQueries separate. A row can be indisready = true while still indisvalid = false. In that case, the index is still part of the write path but is not trustworthy for reads. The two flags answer different questions, so collapsing them would hide the very failure the article wants to expose.

This is also where a misleading intuition often appears: if the database is maintaining the index, perhaps it must already be safe to use. PostgreSQL does not promise that. The concurrent build sequence deliberately stages the object through catalog visibility and write maintenance before it is eligible for query use. A build can therefore leave the index in a state that is active enough to cost work but not finished enough to plan against.

That split is why a useful diagnostic should report both flags. If indisready is true and indisvalid is false, the reader knows they are dealing with a concurrent-build artifact, not merely a missing index. The right next action is typically to drop and recreate it, or rebuild it concurrently, rather than searching for some other planner mystery first.

SourcesPostgreSQL: pg_index (opens a new tab)

indcheckxmin explains why valid is not always immediately usable

Even when indisvalid becomes true, PostgreSQL adds one more wrinkle for old snapshots. The documentation says indcheckxmin forces queries to wait until the xmin of the catalog row is below their transaction horizon because the table may still contain broken HOT chains with incompatible rows that they can see. That means the index can be valid but still temporarily withheld from some queries.

The implementation treats that as a separate state called valid-but-waiting-for-old-snapshots. That label is useful because it reminds the reader that query readiness has a temporal component. The build can be complete enough to mark the index valid, but old transactions can still keep the planner from safely using it. In other words, validity and immediate usability are related but not identical.

This is why the helper does not return readyForQueries based on indisvalid alone. It also checks indcheckxmin and treats that as a blocking condition. That is a conservative interpretation of the documentation and matches the warning that even a completed concurrent build may not be immediately usable for queries.

This state is easy to miss if you only look for the word valid. A reader who is diagnosing a slow or missing index use can easily misread a valid row as proof that the planner should already have switched over. The catalog says otherwise: the remaining snapshot horizon can still delay query use even after the build itself has finished.

SourcesPostgreSQL: CREATE INDEX (opens a new tab)PostgreSQL: pg_index (opens a new tab)

Why indislive stops you from calling dropped indexes active

The remaining boolean in the example is indislive, which PostgreSQL uses to indicate that an index is in the process of being dropped. If it is false, the catalog says the index should be ignored for all purposes, including HOT-safety decisions. That means a row can exist in the catalog without being an active participant in the database at all.

The implementation uses indislive as a gate before any other state becomes meaningful. If the index is not live, it is labeled being-dropped and both readiness booleans are treated as non-actionable. That is consistent with the documentation because a not-live index should be ignored for all purposes. There is no point in asking whether such an object is query-ready.

This extra check prevents a subtle misclassification. Without it, a caller could see indisvalid = false and assume every invalid row is a failed concurrent build leftover. PostgreSQL also uses the catalog to describe an index that is disappearing, and that object should not be diagnosed the same way. The live flag keeps that boundary visible.

That is the larger lesson of the catalog: the flags do not form a single success/failure bit. They describe different ownership questions. Is the index still part of the live schema? Should writes maintain it? Can queries use it? Should old snapshots wait? The helper keeps those questions separate so the output stays honest instead of collapsing everything into one binary label.

SourcesPostgreSQL: pg_index (opens a new tab)

What the example implementation proves, and what it does not

The supplied implementation is intentionally small. One function builds a parameterized catalog query for a named index relation, and another interprets the returned booleans into a state object. The tests prove that a successful rebuild should be treated as query-usable, that an invalid row with insert maintenance still counts as a leftover, and that indcheckxmin blocks query readiness even when the index is otherwise valid.

What the example does not prove is PostgreSQL execution itself. It does not launch a database, force a deadlock, or reproduce a long-running concurrent build. Instead, it encodes the contract the catalog exposes and checks the interpretation layer against representative rows. That is enough to validate the logic of the diagnostic without pretending the fixture has simulated the full engine.

That boundary is important for readers who might otherwise overread a helper like this. A Node test can verify how your application classifies catalog rows, but it cannot by itself demonstrate a live PostgreSQL planner choosing or rejecting an index. The actual engine behavior still belongs to a reader-run database session, using the exact DDL and catalog query from the article.

Still, the example is valuable because it answers the question the browser or client code would need to answer in production: when the catalog says invalid, do not assume query readiness; when it says valid, check whether the snapshot horizon still blocks use; when it says not live, stop treating the index as active. That is the operational decision this article makes visible.

SourcesPostgreSQL: CREATE INDEX (opens a new tab)PostgreSQL: pg_index (opens a new tab)

Operational rules for reading the row

A practical reading order helps when you are on call or triaging a schema issue. First ask whether the index is live. If it is not, the row should be ignored for active-use purposes. Next ask whether it is valid. If it is not, you have a leftover or incomplete artifact that should not be used for queries. Then check whether it is ready for inserts, because that tells you whether write overhead still exists.

After that, inspect indcheckxmin. A valid index can still be temporarily withheld from query planning while old snapshots remain. That is not a contradiction; it is an extra safety gate. The catalog row is telling you that the index is finished enough to be valid but not yet clear of the snapshot history that PostgreSQL still considers dangerous.

The article’s helper turns those rules into three visible states: invalid-leftover, valid-but-waiting-for-old-snapshots, and query-usable. That structure is intentionally narrower than all the catalog possibilities, because the question is not to model every internal lifecycle. The question is to tell a failed concurrent build from a usable index, and to explain why validity alone is not always enough.

That narrowness is a strength. It keeps the output aligned with the operational decision a reader actually has to make: drop and rebuild, wait for snapshots to clear, or trust the index for queries. The catalog gives you the evidence, but the decision still depends on which flag changed and which one has not yet changed.

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

test('a successfully rebuilt live index is usable for queries', () => {
  const row = {
    index_name: 'orders_customer_id_idx',
    table_name: 'orders',
    indisvalid: true,
    indisready: true,
    indislive: true,
    indcheckxmin: false,
  };

  assert.deepEqual(inspectPgIndexRow(row), {
    indexName: 'orders_customer_id_idx',
    tableName: 'orders',
    state: 'query-usable',
    readyForInserts: true,
    readyForQueries: true,
    failedConcurrentBuildLeftover: false,
  });
});

test('an invalid but insert-ready concurrent-build artifact is flagged as a leftover', () => {
  const row = {
    index_name: 'orders_customer_id_idx',
    table_name: 'orders',
    indisvalid: false,
    indisready: true,
    indislive: true,
    indcheckxmin: false,
  };

  const result = inspectPgIndexRow(row);

  assert.equal(result.state, 'invalid-leftover');
  assert.equal(result.failedConcurrentBuildLeftover, true);
  assert.equal(result.readyForInserts, true);
  assert.equal(result.readyForQueries, false);
});

test('a valid index with indcheckxmin is not yet reported query-ready', () => {
  const row = {
    index_name: 'orders_customer_id_idx',
    table_name: 'orders',
    indisvalid: true,
    indisready: true,
    indislive: true,
    indcheckxmin: true,
  };

  const result = inspectPgIndexRow(row);

  assert.equal(result.state, 'valid-but-waiting-for-old-snapshots');
  assert.equal(result.readyForQueries, false);
  assert.equal(result.failedConcurrentBuildLeftover, false);
});

test('the catalog query parameterizes the requested index relation name', () => {
  const query = indexCatalogQuery('public.orders_customer_id_idx');

  assert.deepEqual(query.values, ['public.orders_customer_id_idx']);
  assert.match(query.text, /indisvalid/);
  assert.match(query.text, /indisready/);
});

test('the catalog query rejects an empty index name', () => {
  assert.throws(() => indexCatalogQuery('  '), {
    name: 'TypeError',
    message: 'indexName must be a non-empty string',
  });
});

SourcesPostgreSQL: CREATE INDEX (opens a new tab)PostgreSQL: pg_index (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