SQL: a PRIMARY KEY is UNIQUE plus NOT NULL

A unique constraint allows NULLs - and because NULL never equals NULL, most engines allow many of them. A primary key does not, which is the real difference.

Code
CREATE TABLE a (email VARCHAR(255) UNIQUE);
INSERT INTO a VALUES (NULL), (NULL), (NULL);   -- all three succeed

CREATE TABLE b (email VARCHAR(255) PRIMARY KEY);
INSERT INTO b VALUES (NULL);                   -- rejected

-- PostgreSQL 15+ can forbid the duplicate NULLs:
CREATE TABLE c (email VARCHAR(255) UNIQUE NULLS NOT DISTINCT);
Output
UNIQUE      : 3 rows inserted (NULL, NULL, NULL)
PRIMARY KEY : ERROR: null value in column "email" violates not-null constraint

-- A table can have many UNIQUE constraints and exactly one PRIMARY KEY.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25