Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users VALUES (1, 'a@x.com'), (2, NULL), (3, NULL);
SELECT id, email FROM users ORDER BY id;| id | |
|---|---|
| 1 | a@x.com |
| 2 | NULL |
| 3 | NULL |
Two NULL emails are accepted, because NULL is not equal to NULL, so they do not clash. A second identical email is rejected:
sql
CREATE TABLE users2 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users2 VALUES (1, 'a@x.com'), (2, 'a@x.com');
-- error on purposetext
Error: UNIQUE constraint failed: users2.emailThe primary key rejects a duplicate id just the same:
sql
CREATE TABLE users3 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users3 VALUES (1, 'a@x.com'), (1, 'b@x.com');
-- error on purposetext
Error: UNIQUE constraint failed: users3.idOne SQLite quirk: unless the table is declared STRICT or WITHOUT ROWID, or the key is an INTEGER PRIMARY KEY, a primary key column accepts NULL for historical reasons. Declare key columns NOT NULL explicitly to be safe.
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users VALUES (1, 'a@x.com'), (2, NULL), (3, NULL);
SELECT id, email FROM users ORDER BY id;
-- error on purpose
CREATE TABLE users2 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users2 VALUES (1, 'a@x.com'), (2, 'a@x.com');
-- error on purpose
CREATE TABLE users3 (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users3 VALUES (1, 'a@x.com'), (1, 'b@x.com');Checked on SQLite 3.46.1, run twice with identical output.
Key points
- One primary key per table; many unique constraints
- Primary key columns are unique and not null
- Unique columns usually allow several NULLs
- Both are backed by a unique index
Common mistakes
- Assuming UNIQUE also means NOT NULL
- Relying on SQLite to reject NULL in a non-integer primary key
Follow-ups
- What is a natural key versus a surrogate key?
- How would you allow only one NULL in a unique column?
Tips
- Mention the NULL behaviour of UNIQUE