PostgreSQL error: duplicate key value violates unique constraint

ERROR:  duplicate key value violates unique constraint "users_email_key"
DETAIL:  Key (email)=([email protected]) already exists.

An INSERT or UPDATE tried to create a second row with the same value in a column (or set of columns) covered by a unique constraint or unique index. The DETAIL line tells you exactly which constraint and which value — the diagnosis starts from there.

What this error means

The constraint worked: PostgreSQL guarantees uniqueness even under concurrency, and this error is that guarantee firing. Two things worth knowing beyond the obvious:

Common causes

How to diagnose it

-- Quale vincolo, quali colonne:
\d users

-- Sospetto "sequenza rimasta indietro" (errore sulla _pkey con id seriali):
SELECT max(id) FROM users;
SELECT last_value FROM users_id_seq;
-- se last_value <= max(id), è questa la causa

If the constraint is on a business key (email, SKU, …) rather than the primary key, look at where the value in DETAIL comes from: same user double-submitting, retry logic, or two code paths creating the same entity.

How to fix it

🔍 Related reading: Choosing the right index — unique, partial and expression indexes, and what they cost on writes.