Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, deleted_at TEXT);
INSERT INTO accounts VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);The query as written:
sql
INSERT INTO accounts (email) VALUES ('ana@x.com'); -- error on purposetext
Error: UNIQUE constraint failed: accounts.emailThe old account 1 is marked deleted, but its row still holds the email, so the table-wide UNIQUE constraint rejects the new registration.
A corrected version:
sql
CREATE TABLE accounts2 (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX accounts2_live_email ON accounts2 (email) WHERE deleted_at IS NULL;
INSERT INTO accounts2 VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
INSERT INTO accounts2 (email) VALUES ('ana@x.com');
SELECT id, email, deleted_at FROM accounts2 ORDER BY id;| id | deleted_at | |
|---|---|---|
| 1 | ana@x.com | 2026-02-01 |
| 2 | ben@x.com | NULL |
| 3 | ana@x.com | NULL |
With the partial index, the deleted row is ignored by the uniqueness check, so Ana can register again and both rows exist side by side. A second live row with the same email would still fail. Queries on live accounts should add deleted_at IS NULL, which also lets them use the partial index. The same index definition works in PostgreSQL, where ON CONFLICT targets must repeat the predicate.
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, deleted_at TEXT);
INSERT INTO accounts VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
-- error on purpose
INSERT INTO accounts (email) VALUES ('ana@x.com');
CREATE TABLE accounts2 (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX accounts2_live_email ON accounts2 (email) WHERE deleted_at IS NULL;
INSERT INTO accounts2 VALUES (1, 'ana@x.com', '2026-02-01'), (2, 'ben@x.com', NULL);
INSERT INTO accounts2 (email) VALUES ('ana@x.com');
SELECT id, email, deleted_at FROM accounts2 ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Plain UNIQUE counts deleted rows
- Partial unique index limits the rule to live rows
- Live queries should filter deleted_at IS NULL
- Works in SQLite and PostgreSQL
Common mistakes
- Appending a suffix to deleted emails as a workaround
- Forgetting the predicate in queries so the index is unused
Follow-ups
- How would you restore a deleted account whose email was reused?
- What other constraints need the same treatment?
Tips
- Show the failing insert first