Skip to main content
Database & ORM · Developer Error Resolution Lab

Fix PrismaClientKnownRequestError P2002: 'Unique constraint failed on the fields: (`email`)'

Handle duplicate key violations gracefully with `upsert`, `createMany({ skipDuplicates: true })`, or sequence resynchronization in PostgreSQL.

Triggered Error Message:

PrismaClientKnownRequestError: Invalid `prisma.user.create()` invocation: Unique constraint failed on the fields: (`email`)

Customize Solution for Your Environment
-- If P2002 happens on 'id' (autoincrement out of sync in Postgres), run:
SELECT setval(pg_get_serial_sequence('"User"', 'id'), COALESCE(MAX(id), 1)) FROM "User";

-- Or switch to collision-free time-ordered UUIDv7 via Castov CLI:
-- npx castov id

Root Cause & Mechanism Analysis

Why does this error occur?

An `INSERT` or `UPDATE` attempted to write a value that already exists in a `@unique` or `@id` column, or an auto-incrementing PostgreSQL `SERIAL` sequence fell out of sync after manual data imports.

Frequently Asked Questions

Why does P2002 happen on `id` even when I don't pass `id` in `prisma.create()`?
If rows were seeded with explicit IDs, PostgreSQL's internal sequence counter is not incremented automatically. Running `setval(pg_get_serial_sequence(...))` resyncs the sequence.
DEVSECOPS & CI/CD PARTNER2 Slots Open

Need Zero-Knowledge .env Secret Sync Across Your Engineering Team?

Explore Castov Env Vault for client-side AES-256-GCM encrypted environment sharing, or sponsor this engineering hub.

Browse All 54 Guides