Unique Constraint Cannot Be NOT VALID
NOT VALID only applies to foreign-key, CHECK, and not-null constraints, so a UNIQUE addition must scan and dedupe the whole table in the same statement.
Code
-- NOT VALID 的本意:先加约束挡新数据,存量行留到 VALIDATE 再查
-- 但它目前只允许 foreign-key、CHECK 与 not-null 约束
CREATE TEMP TABLE members (
member_id int PRIMARY KEY,
email text NOT NULL
);
INSERT INTO members VALUES (1, '[email protected]'), (2, '[email protected]'); -- 故意留重复
-- ADD CONSTRAINT UNIQUE 带 NOT VALID 会被直接拒绝(rejected)
ALTER TABLE members
ADD CONSTRAINT members_email_unique UNIQUE (email) NOT VALID;
-- ERROR: unique constraints cannot be marked NOT VALID
-- 唯一约束背后就是唯一索引,建索引必须全表扫,没有“先挡新数据”的半途形态
-- 在线加唯一约束的正解(大表):CREATE UNIQUE INDEX CONCURRENTLY 建好索引,
-- 再用 UNIQUE USING INDEX 挂成约束;演示库上直接建等价索引
DELETE FROM members a USING members b
WHERE a.member_id > b.member_id AND a.email = b.email;
CREATE UNIQUE INDEX members_email_uidx ON members (email);
ALTER TABLE members ADD CONSTRAINT members_email_unique
UNIQUE USING INDEX members_email_uidx;
DROP TABLE members;How it works
INSERT / DELETE / CREATE / ALTER statements share the script, touching members.
members is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: a WHERE clause filtering the rows one statement applies to; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out.
Using it
Nothing outside the file is needed: the session-local tables it touches (members) are created by the file itself — point it at a scratch database and run the whole thing.
Key statements
DELETE FROM members a USING members b
WHERE a.member_id > b.member_id AND a.email = b.email;
CREATE TEMP TABLE members (
member_id int PRIMARY KEY,
email text NOT NULL
);
INSERT INTO members VALUES (1, '[email protected]'), (2, '[email protected]'); -- 故意留重复
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- `members` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.