Full answer
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active ON subs(user_id) WHERE status = 'active';
INSERT INTO subs VALUES (1, 1, 'cancelled'), (2, 1, 'cancelled'), (3, 1, 'active');
SELECT * FROM subs ORDER BY id;| id | user_id | status |
|---|---|---|
| 1 | 1 | cancelled |
| 2 | 1 | cancelled |
| 3 | 1 | active |
User 1 has one active and two cancelled subscriptions, which is allowed. A second active one fails:
sql
CREATE TABLE s2 (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');
-- error on purposetext
Error: UNIQUE constraint failed: s2.user_idA plain UNIQUE (user_id, status) would wrongly block a second cancelled row. Application checks ("select, then insert if none") race under concurrency: two requests can both see no active row and both insert. The index makes the database the referee.
PostgreSQL behaves the same:
sql
CREATE TABLE s2 (id int PRIMARY KEY, user_id int, status text);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');
-- error on purposetext
Error: duplicate key value violates unique constraint "one_active2"sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active ON subs(user_id) WHERE status = 'active';
INSERT INTO subs VALUES (1, 1, 'cancelled'), (2, 1, 'cancelled'), (3, 1, 'active');
SELECT * FROM subs ORDER BY id;
-- error on purpose
CREATE TABLE s2 (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- A partial unique index enforces uniqueness on a subset of rows
- Rows outside the WHERE clause are not constrained
- UNIQUE (user_id, status) is too strict
- Check-then-insert in the application races
Common mistakes
- Enforcing the rule only in application code
- Using a composite unique that blocks repeated cancelled rows
Follow-ups
- How would you enforce no overlapping booking periods?
- What happens to the index when a row changes status?
Tips
- Mention the race condition explicitly