pg_stat_progress_create_index Tracks Build Phases

Poll pg_stat_progress_create_index for phase, blocks_done, and tuples_done while CREATE INDEX CONCURRENTLY runs in another backend.

SqlResilience

Code

snippet
-- 在另一个会话执行长构建(本视图每个在建索引的后端一行):
-- CREATE INDEX CONCURRENTLY idx_events_at ON events (at);

-- 本会话轮询进度:官方示例即用 nullif 防 0 除
SELECT
    pid,
    command,
    phase,
    blocks_done,
    blocks_total,
    round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS blocks_pct,
    tuples_done,
    tuples_total,
    lockers_done,
    lockers_total
FROM pg_stat_progress_create_index;

-- 普通建索引只有 initializing 与 building index 两个阶段;
-- CONCURRENTLY 会依次经过等待写入者、验证扫描/排序/回扫、等待旧快照等阶段
-- 构建中途失败会留下 INVALID 索引:从 pg_index 复核后再清理重建
SELECT indexrelid::regclass AS index_name, indisvalid
FROM pg_index
WHERE NOT indisvalid;

-- 等构建收尾时看一眼锁等待:CONCURRENTLY 的后段要等旧事务退出
SELECT pid, wait_event_type, wait_event, state
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';

How the snippet works

The file runs SELECT statements, touching pg_stat_progress_create_index, pg_index and pg_stat_activity.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch.

Using it

The pg_stat_progress_create_index table is the working surface here.

Key statements

SELECT pid, wait_event_type, wait_event, state
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
SELECT indexrelid::regclass AS index_name, indisvalid
FROM pg_index
WHERE NOT indisvalid;
SELECT
    pid,
    command,
    phase,
    blocks_done,
    blocks_total,
    round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS blocks_pct,
    tuples_done,
    tuples_total,
    lockers_done,
    lockers_total
FROM pg_stat_progress_create_index;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`pg_stat_progress_create_index`, `pg_index`, `pg_stat_activity` — referenced directly, no join needed.