Primary Key Using Existing Index
Promote a unique index built with CREATE INDEX CONCURRENTLY to a primary key with ADD CONSTRAINT USING INDEX, without rebuilding the table.
Code
-- 大表补主键的两步法:先并发建唯一索引,再一步转正为约束
-- ALTER 这一步是快速操作,不做全表重建(可能只为标 NOT NULL 扫一遍表)
CREATE TABLE import_batches (
id bigint NOT NULL,
source text NOT NULL,
loaded_at timestamptz NOT NULL DEFAULT now()
);
-- 第一步:CONCURRENTLY 建唯一索引,建索引期间不阻塞写入
CREATE UNIQUE INDEX CONCURRENTLY idx_import_batches_id
ON import_batches (id);
-- 第二步:把 existing index 收编为主键约束,索引名随约束改名
ALTER TABLE import_batches
ADD CONSTRAINT import_batches_pkey PRIMARY KEY USING INDEX idx_import_batches_id;
INSERT INTO import_batches (id, source) VALUES (1, 'crm') RETURNING id;
-- 转正后约束与普通主键完全一致:重复 id 被 pkey 拦下
-- ERROR: duplicate key value violates unique constraint "import_batches_pkey"
-- INSERT INTO import_batches (id, source) VALUES (1, 'crm');
-- 限制:索引不能含表达式列、不能是部分索引,必须是默认排序的 b-treeWhat the code does
Several statements share this file — INSERT / CREATE / ALTER, with import_batches among the objects involved.
Mechanically, the statements are built from: a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; DEFAULT values filling omitted columns.
Using it
Run the statement against the import_batches table.
Key statements
CREATE TABLE import_batches (
id bigint NOT NULL,
source text NOT NULL,
loaded_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX CONCURRENTLY idx_import_batches_id
ON import_batches (id);
INSERT INTO import_batches (id, source) VALUES (1, 'crm') RETURNING id;
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `import_batches` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.