Predict the output
A partial unique index allows only one active plan per user. What does the last SELECT print?
CREATE TABLE subs (user_id int, plan text, active bool);
CREATE UNIQUE INDEX one_active ON subs (user_id) WHERE active;
INSERT INTO subs VALUES
(1, 'basic', false), (1, 'pro', false), (1, 'max', true);
SELECT count(*) FROM subs WHERE user_id = 1;Hint 1 of 1
Which rows are in the index?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3
Correct. Inactive rows aren't in the index, so only the single active row is checked for uniqueness.
A partial index only holds rows that match its WHERE clause. The two inactive rows aren't in it, so uniqueness is checked only among active rows, and there is just one.
Why not the others?
- B
1. Inactive duplicates are allowed; the index only covers active rows. - C A unique violation on the second row. The second row is inactive, so it's outside the partial index.
- D
2. All three rows are inserted in one statement and none conflicts.
| count |
|---|
| 3 |
(1 row)