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.

SqlData Integrity

Code

snippet
-- 需求:一个用户对一个项目只能有一条角色分配
-- 错误建模:两个单列 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

FAQ

Which objects does the SQL touch?
`assignments`.