Prisma Errors
databasesprismaTroubleshootingBeginner
Prisma Error P2002: Unique constraint failed
How to troubleshoot and fix Prisma error P2002 when attempting to insert or update a record with a duplicate unique field value.
Verified: 2026-10-01
Tested on:prisma 6.x
Platforms:
node
#prisma#errors#p2002#unique-constraint#database
Prisma Error P2002: Unique constraint failed
Error Message
Invalid `prisma.user.create()` invocation:
Unique constraint failed on the constraint: `users_email_key`
at ...
code: 'P2002',
clientVersion: '6.x.x',
meta: { modelName: 'User', target: [ 'email' ] }Symptoms
prisma.user.create(),createMany(), orupdate()rejects with aPrismaClientKnownRequestError.- Error code is
P2002. meta.targetlists the conflicting unique column (e.g.['email']or['slug']).
Why It Happens
In your schema.prisma, a field is annotated with @unique (or a model with @@unique([...])). The database rejected the insert/update operation because a row with the exact same value already exists.
How to Fix It
Solution 1: Use upsert (Update if exists, Create if new)
const user = await prisma.user.upsert({
where: { email: "user@example.com" },
update: { name: "Updated Name" },
create: { email: "user@example.com", name: "New Name" },
});Solution 2: Catch P2002 in API Route Handlers
import { Prisma } from "@prisma/client";
try {
const user = await prisma.user.create({ data });
return Response.json(user, { status: 201 });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
return Response.json(
{ error: "An account with this email already exists." },
{ status: 409 }
);
}
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}Related Guides
Docker: no space left on device / Disk space issues
Fix no space left on device errors in Docker by cleaning dangling images, build caches, stopped containers, and unattached volumes.
Prisma Error P2025: Record to update or delete not found
How to troubleshoot and fix Prisma error P2025 when attempting to update, delete, or connect a record that does not exist in the database.