← Back to SQL, page 10

sql-0183 · Hard senior

How would you allow only one active subscription per user, while allowing any number of cancelled ones?

Create a partial unique index: CREATE UNIQUE INDEX ... ON subscriptions(user_id) WHERE status = 'active'. Only active rows are in the index, so a second active row for the same user is rejected while cancelled rows are unrestricted. SQLite and PostgreSQL both support this.

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;
iduser_idstatus
11cancelled
21cancelled
31active

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 purpose
text
Error: UNIQUE constraint failed: s2.user_id

A 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 purpose
text
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