← Back to SQL, page 9

sql-0175 · Easy fresher

How do a primary key and a unique constraint differ?

A table has at most one primary key; its columns must be unique and NOT NULL, and it is the row's main identifier that foreign keys usually reference. A table can have many unique constraints, and in most engines a unique column may hold several NULLs. Both are enforced with a unique index.

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;
idemail
1a@x.com
2NULL
3NULL

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

The 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 purpose
text
Error: UNIQUE constraint failed: users3.id

One 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