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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- Which tables does the SQL touch?
- The references are `pg_indexes`, `pg_class`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.