Partial Unique Index Active Row Rule

Enforce one active row per key with a partial unique index: uniqueness applies only inside the WHERE predicate, history rows stay unlimited.

SqlData Integrity

Code

snippet
CREATE TABLE subscriptions (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id    bigint NOT NULL,
    plan       text   NOT NULL,
    active     boolean NOT NULL DEFAULT true,
    created_at timestamptz NOT NULL DEFAULT now()
);

-- 部分唯一索引:只约束 active 行,历史行不受限
CREATE UNIQUE INDEX one_active_subscription
    ON subscriptions (user_id) WHERE active;

INSERT INTO subscriptions (user_id, plan) VALUES (42, 'pro');   -- 第一次:成功

-- 同一用户再插一条 active:违反唯一索引(dup key, index 名即报错来源)
-- INSERT INTO subscriptions (user_id, plan) VALUES (42, 'team');

-- 归档旧行后即可换新:active=false 不在约束范围内
UPDATE subscriptions SET active = false WHERE user_id = 42;
INSERT INTO subscriptions (user_id, plan) VALUES (42, 'team');  -- 成功

SELECT user_id, plan, active FROM subscriptions ORDER BY created_at;
DROP TABLE subscriptions;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with subscriptions among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; 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; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

The subscriptions table is the working surface here.

Statements that matter

INSERT INTO subscriptions (user_id, plan) VALUES (42, 'pro');   -- 第一次:成功
UPDATE subscriptions SET active = false WHERE user_id = 42;
INSERT INTO subscriptions (user_id, plan) VALUES (42, 'team');  -- 成功
SELECT user_id, plan, active FROM subscriptions ORDER BY created_at;
CREATE UNIQUE INDEX one_active_subscription
ON subscriptions (user_id) WHERE active;

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`subscriptions` — referenced directly, no join needed.