Menu▾
mediumMaybank · indexing

Enforce uniqueness the way a UNIQUE constraint actually works

customers.email currently happens to hold unique values, but nothing in the schema enforces it — a duplicate could be inserted tomorrow. Enforce it by creating a UNIQUE index directly on customers.email, rather than going through ADD CONSTRAINT ... UNIQUE.

(They end up equivalent — a UNIQUE constraint is implemented as a unique index under the hood — but writing the index form directly is worth practicing, since it's the only form available when the unique rule needs to be partial or expression-based, which a plain constraint can't do.)

Schema

▸customers
idINT
emailTEXT
nameTEXT

Example input

Why

CREATE UNIQUE INDEX and ALTER TABLE ... ADD CONSTRAINT ... UNIQUE end up building the identical structure — Postgres implements every UNIQUE constraint as a unique index, the same way it implements every PRIMARY KEY as one. The constraint form is really just a named wrapper around the index form. The index form is strictly more capable: it accepts a WHERE clause for a partial index ("unique among active rows only") and can index an expression rather than a bare column, and neither of those is expressible through ADD CONSTRAINT. Reaching for the index form directly, as this question asked, is the version that generalizes to those cases later.

↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.