Unique constraint

A database rule that refuses duplicates, such as two accounts with the same email or two identical memberships.

stop duplicate emailsmake sure this value only appears oncetwo users got the same usernameuniq constraintunqiue constraintduplicate key value violates unique constraintonly one booking per user and datethe same person managed to sign up twicehow do I prevent duplicate records

See it

Live demo coming soon

What it is

A unique constraint is the database's refusal to store the same value twice in one column, or the same combination twice across several columns. UNIQUE (email) protects one column; UNIQUE (user_id, date) protects a pair. Unlike a primary key, a table can have several unique constraints, and in most databases a nullable unique column can still hold several NULL values because NULL is not treated as equal to itself.

Reach for one whenever duplication would make the data wrong: usernames, external payment ids, one membership per user and workspace, or one daily booking per room. Put the rule in the database even if the form already checks, because two requests can both pass an application check before either one inserts.

Gotcha: the constrained columns define exactly what counts as a duplicate. UNIQUE (tenant_id, email) allows the same email in different tenants; UNIQUE (email) does not. Also treat the resulting conflict as a normal outcome in application code. The constraint closes the race, but it reports the loser as an error unless you catch it or use an upsert deliberately. PostgreSQL phrases it as 'duplicate key value violates unique constraint users_email_key', and that generated name is the table, the column, and the suffix _key, so the error already tells you which rule you hit.

Ask AI for it

Add PostgreSQL UNIQUE constraints for every true no-duplicates rule in this schema. Use a single-column constraint for globally unique values and a composite constraint such as UNIQUE (tenant_id, email) when uniqueness is scoped. Keep the constraint in the database instead of relying on a SELECT-before-INSERT check, then catch SQLSTATE 23505 and return a field-specific conflict response. For nullable values, state whether multiple NULLs are valid and use UNIQUE NULLS NOT DISTINCT on PostgreSQL 15 or later when they are not. Where uniqueness applies only to live rows, use CREATE UNIQUE INDEX ... WHERE deleted_at IS NULL instead of a table constraint. Include the ALTER TABLE statements and concurrent request tests proving that exactly one duplicate insert succeeds.

You might have meant

primary keyforeign keydatabase constraintrace conditionupsert