How to ensure only a single row with a certain value
-
02-03-2021 - |
문제
Given this table:
CREATE TABLE rollouts
(
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
device_id TEXT NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT FALSE
);
How can I ensure that for a given device_id
, there is only ever one active rollout? Multiple inactive ones are fine, so a simple unique index doesn't cut it.
해결책
You can use a partial unique index:
create unique index on rollouts (device_id)
where is_active;
제휴하지 않습니다 dba.stackexchange