Composite Unique Versus Two Uniques
UNIQUE (user_id, project_id) allows one user on many projects and one project on many users, while two single-column uniques would forbid both.
Code
-- 需求:一个用户对一个项目只能有一条角色分配
-- 错误建模:两个单列 UNIQUE 会把 user_id、project_id 各自锁死成一对一
-- CREATE UNIQUE INDEX ON assignments (user_id);
-- CREATE UNIQUE INDEX ON assignments (project_id); -- 过强
CREATE TABLE assignments (
id integer PRIMARY KEY,
user_id integer NOT NULL,
project_id integer NOT NULL,
role text NOT NULL,
-- 组合唯一(composite UNIQUE):只锁 (user_id, project_id) 这一对
UNIQUE (user_id, project_id)
);
INSERT INTO assignments (id, user_id, project_id, role) VALUES
(1, 10, 100, 'owner'),
(2, 10, 200, 'member'), -- 同一用户参与第二个项目:组合唯一放行
(3, 20, 100, 'member'); -- 同一项目里第二个用户:也放行
-- 同一 (user_id, project_id) 组合再出现:被组合 UNIQUE 拦下
-- ERROR: duplicate key value violates unique constraint "assignments_user_id_project_id_key"
-- INSERT INTO assignments (id, user_id, project_id, role) VALUES (4, 10, 100, 'member');How the snippet works
What runs here is INSERT / CREATE — assignments are the objects involved.
Breaking the statements into their working parts: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out.
Applying it
The assignments table is the working surface here.
Statements that matter
CREATE TABLE assignments (
id integer PRIMARY KEY,
user_id integer NOT NULL,
project_id integer NOT NULL,
role text NOT NULL,
UNIQUE (user_id, project_id)
);
INSERT INTO assignments (id, user_id, project_id, role) VALUES
(1, 10, 100, 'owner'),
(2, 10, 200, 'member'), -- 同一用户参与第二个项目:组合唯一放行
(3, 20, 100, 'member'); -- 同一项目里第二个用户:也放行
Interactive Tools for This Topic
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.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.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 objects does the SQL touch?
- `assignments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.