Detect Duplicates Before Adding Unique Constraint

Group and count existing rows with HAVING before adding a UNIQUE constraint, because the constraint build fails while duplicated keys remain.

SqlData Integrity

Code

snippet
-- 给存量表加 UNIQUE 约束前,先 detect 已有 duplicates:
-- 约束构建会全表校验,任何重复键都会让整条 ALTER 失败
CREATE TEMP TABLE device_tokens (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    token text NOT NULL
);
INSERT INTO device_tokens (token) VALUES ('tok-1'), ('tok-2'), ('tok-1');

-- 1) 查重:GROUP BY + HAVING 列出违规键及其行数
SELECT token, COUNT(*) AS copies
FROM device_tokens
GROUP BY token
HAVING COUNT(*) > 1;

-- 2) 此时直接加约束会失败:
--    ERROR: could not create unique index "token_unique"
--    DETAIL: Key (token)=(tok-1) is duplicated.

-- 3) 清理:每个 token 只保留 id 最小的一行
DELETE FROM device_tokens d
USING device_tokens k
WHERE d.token = k.token AND d.id > k.id;

-- 4) 重试:约束创建成功,之后的重复 INSERT 会被唯一约束拒绝
ALTER TABLE device_tokens ADD CONSTRAINT token_unique UNIQUE (token);

What the code does

SELECT / INSERT / DELETE / CREATE / ALTER statements share the script, touching device_tokens.

device_tokens is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

In terms of clauses, the statements use: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; 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.

Applying it

Setup is internal: the session-local tables it queries (device_tokens) are made by the file, so a single complete run against a scratch database suffices.

Statements that matter

SELECT token, COUNT(*) AS copies
FROM device_tokens
GROUP BY token
HAVING COUNT(*) > 1;
CREATE TEMP TABLE device_tokens (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    token text NOT NULL
);
DELETE FROM device_tokens d
USING device_tokens k
WHERE d.token = k.token AND d.id > k.id;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `device_tokens`.