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.

SqlData Integrity

Code

snippet
-- 大表补主键的两步法:先并发建唯一索引,再一步转正为约束
-- 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-tree

What 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

FAQ

Which tables appear in this script?
`import_batches` — referenced directly, no join needed.