A unique constraint requires the values in a column (or column combination) to be distinct. Unlike a primary key, a table may carry any number of unique constraints, and the columns may be nullable. PostgreSQL treats two NULLs as distinct from each other, so multiple NULL rows are accepted — a subtlety that surprises many people.
The columns whose values must be pairwise distinct. Several columns form a composite unique constraint.
Returns:A unique constraint has no return value. It creates a unique index automatically (named `
__key`) and rejects duplicates with `duplicate key value violates unique constraint "..."`.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT 'rows with NULL phone' AS step, (SELECT count(*)::TEXT FROM users WHERE phone IS NULL) AS result
UNION ALL SELECT 'duplicate email insert',
(SELECT pg_try('INSERT INTO users VALUES (4,''a@example.com'',''222'')'))
UNION ALL SELECT 'total rows', (SELECT count(*)::TEXT FROM users)
step | result
------------------------+------------------------------------------------------------------
rows with NULL phone | 2
duplicate email insert | duplicate key value violates unique constraint "users_email_key"
total rows | 3
(3 rows)
ASQL treats NULL as 'unknown', and two unknown values cannot be judged equal. PostgreSQL defaults to NULLS DISTINCT, which considers NULLs different from each other. If your business rule requires at most one NULL, use UNIQUE NULLS NOT DISTINCT.
QHow does a UNIQUE constraint differ from a unique index?
AA unique constraint is a schema object: it appears in pg_constraint and can be referenced by foreign keys. A unique index is only an index and survives dropping a constraint. Constraint indexes are named `
__key`, while a unique index can be named freely.
Web-Tutorial Tech Team
A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.