Prisma error P2002: Unique constraint failed on the fields

Prisma·Sep 12, 2026·beginner·
Quick answer

P2002 means you're trying to insert or update a record with a value that already exists in a column marked `@unique`. Catch it explicitly with a try/catch and check `error.code === 'P2002'`, or query first to give the user a clear message instead of a raw 500.

What causes this error

Any field marked @unique (or a @@unique composite) in your Prisma schema will throw P2002 if you attempt to create or update a record that violates that constraint — most commonly duplicate emails, usernames, or slugs.

The Fix

import { Prisma } from '@prisma/client';

try {
  await prisma.user.create({ data: { email } });
} catch (err) {
  if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
    const field = (err.meta?.target as string[])?.join(', ');
    throw new ApiError(409, `A user with this ${field} already exists`);
  }
  throw err;
}

Common causes / variations

  • Duplicate email/username sign-up attempts
  • Re-running a seed script without clearing existing data first
  • Race conditions — two requests creating the same record simultaneously
  • Composite unique constraints (`@@unique([a, b])`) failing on the combination, not a single field

Related errors

See also: P2025 Record to update not found, and PrismaClientInitializationError.

Was this fix helpful?

Comments

Loading comments...

Fix: Prisma P2002 Unique constraint failed | BugFixer | BugFixer