pg_get_indexdef Rebuilds Index DDL

pg_get_indexdef decompiles a catalog entry back into its CREATE INDEX statement, so migrations and docs can show real DDL instead of hand-copied definitions.

SqlCli Tooling

Code

snippet
CREATE TABLE readings (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    station_code text NOT NULL,
    taken_at     timestamptz NOT NULL
);

CREATE INDEX readings_station_time
    ON readings (station_code, taken_at DESC);

CREATE UNIQUE INDEX readings_station_time_unique
    ON readings (station_code, taken_at);

-- 反编译重建:catalog 条目还原成 CREATE INDEX 语句(非原始提交文本)
SELECT indexname,
       pg_get_indexdef(c.oid) AS definition
FROM pg_indexes i
JOIN pg_class c ON c.relname = i.indexname
WHERE i.tablename = 'readings'
ORDER BY indexname;

-- 带列号:只还原单个索引列的定义;pretty=true 输出更易读
SELECT pg_get_indexdef('readings_station_time'::regclass, 2, true) AS col2;

-- 同族函数:pg_get_viewdef 还原视图 SELECT,pg_get_functiondef 还原函数体

Inside the snippet

SELECT / CREATE statements share the script, touching pg_indexes and pg_class.

Mechanically, the statements are built from: one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Run the statement against the pg_indexes table.

The core lines of the flow

SELECT indexname,
       pg_get_indexdef(c.oid) AS definition
FROM pg_indexes i
JOIN pg_class c ON c.relname = i.indexname
WHERE i.tablename = 'readings'
ORDER BY indexname;
CREATE TABLE readings (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    station_code text NOT NULL,
    taken_at     timestamptz NOT NULL
);
CREATE UNIQUE INDEX readings_station_time_unique
    ON readings (station_code, taken_at);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `pg_indexes`, `pg_class`, with one join tying the pair together.