PrismaDatabaseError Fix2026 Updated

Prisma P2002 Unique Constraint Failed— Fixed [Complete Guide 2026]

Also covers: duplicate email · duplicate username · upsert pattern · composite unique

January 20266 min readPrisma · PostgreSQL · Node.js

⚡ The Error You Are Seeing

Error
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation:

Unique constraint failed on the fields: (`email`)

  code: 'P2002',
  meta: { target: [ 'email' ] }

What Causes Prisma P2002

Prisma throws P2002 when you attempt to create or update a record with a value that already exists in a column marked @unique in your schema. The most common triggers:

The key field to inspect is error.meta.target — it tells you exactly which field(s) caused the conflict.

1

Catch and Handle the P2002 Error

Best practice — never let P2002 crash your server
3 min

The first thing to do is catch the error properly and return a clear user-facing message instead of a 500 crash.

lib/prisma-error.ts
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";

export function isPrismaError(error: unknown, code: string): boolean {
  return (
    error instanceof PrismaClientKnownRequestError &&
    error.code === code
  );
}

export function getUniqueField(error: unknown): string | null {
  if (error instanceof PrismaClientKnownRequestError) {
    const target = error.meta?.target as string[] | undefined;
    return target?.[0] ?? null;
  }
  return null;
}
app/api/register/route.ts
import { prisma } from "@/lib/prisma";
import { isPrismaError, getUniqueField } from "@/lib/prisma-error";

export async function POST(request: Request) {
  const { email, name, password } = await request.json();

  try {
    const user = await prisma.user.create({
      data: { email, name, password },
    });
    return Response.json({ user });
  } catch (error) {
    if (isPrismaError(error, "P2002")) {
      const field = getUniqueField(error);
      return Response.json(
        { error: `${field ?? "Value"} already in use` },
        { status: 409 }
      );
    }
    throw error; // re-throw unexpected errors
  }
}

Always re-throw errors that are not P2002 — otherwise you will silently swallow unexpected database errors.

2

Use upsert Instead of create

Atomic — no race conditions, no P2002
2 min

If your intent is 'create if not exists, update if exists', use upsert. This is atomic — it eliminates race conditions entirely.

upsert pattern
// BEFORE — throws P2002 on duplicate email
const user = await prisma.user.create({
  data: { email, name, role: "member" },
});

// AFTER — safe upsert, never throws P2002
const user = await prisma.user.upsert({
  where: { email },
  update: { name }, // fields to update if record exists
  create: { email, name, role: "member" }, // fields for new record
});
upsert for settings/config tables
// Great for seeding or syncing external data
const config = await prisma.appConfig.upsert({
  where: { key: "maintenance_mode" },
  update: { value: "false" },
  create: { key: "maintenance_mode", value: "false" },
});
3

Check Before Inserting (findUnique)

Use when you need to return specific validation errors
3 min

When you need granular validation messages per field, check first with findUnique before creating.

findUnique + create is NOT atomic — a race condition can still cause P2002 between the two calls. For high-traffic endpoints, prefer upsert or catch P2002 directly.

validation before insert
export async function registerUser(email: string, name: string) {
  // Check for existing email first
  const existing = await prisma.user.findUnique({
    where: { email },
    select: { id: true }, // only fetch what you need
  });

  if (existing) {
    return {
      error: "An account with this email already exists",
      field: "email",
    };
  }

  // Safe to create — but still wrap in try/catch for race conditions
  try {
    const user = await prisma.user.create({
      data: { email, name },
    });
    return { user };
  } catch (error) {
    if (isPrismaError(error, "P2002")) {
      return { error: "Email already in use", field: "email" };
    }
    throw error;
  }
}
4

Composite Unique Constraints

@@unique([fieldA, fieldB]) in schema.prisma
3 min

Composite unique constraints enforce uniqueness across multiple fields together. The error looks the same but error.meta.target will contain multiple field names.

schema.prisma — composite unique
model TeamMember {
  id         String @id @default(cuid())
  userId     String
  teamId     String
  role       String

  // A user can only belong to a team once
  @@unique([userId, teamId])
}
handling composite P2002
try {
  await prisma.teamMember.create({
    data: { userId, teamId, role: "member" },
  });
} catch (error) {
  if (isPrismaError(error, "P2002")) {
    // error.meta.target = ['userId', 'teamId']
    const fields = (error as PrismaClientKnownRequestError)
      .meta?.target as string[];

    if (fields.includes("userId") && fields.includes("teamId")) {
      return { error: "User is already a member of this team" };
    }
  }
  throw error;
}
5

Database Has Stale Duplicate Data

Seed scripts · data imports · migration drift
3 min

If P2002 appears after running a seed script or data import, your database likely contains rows that violate the unique constraint you added later. Fix the data first.

terminal — inspect duplicates with Prisma Studio
# Open Prisma Studio to inspect and delete duplicate rows
npx prisma studio

# Or query duplicates with raw SQL (PostgreSQL)
npx prisma db execute --stdin <<'SQL'
SELECT email, COUNT(*) as count
FROM "User"
GROUP BY email
HAVING COUNT(*) > 1;
SQL
seed.ts — guard against duplicate seeding
// Use upsert in seeds to make them idempotent
async function seed() {
  await prisma.user.upsert({
    where: { email: "admin@example.com" },
    update: {},
    create: {
      email: "admin@example.com",
      name: "Admin",
      role: "admin",
    },
  });
}

seed().catch(console.error).finally(() => prisma.$disconnect());

Prevention Checklist

Frequently Asked Questions

What is Prisma error P2002?+
P2002 means 'Unique constraint failed' — you tried to insert or update a record with a value that already exists in a column marked @unique in your Prisma schema. Most commonly triggered by duplicate email addresses, usernames, or slug fields.
How do I fix Prisma P2002 unique constraint failed on email?+
Catch the PrismaClientKnownRequestError and check error.code === 'P2002'. Then return a user-friendly message like 'Email already in use' instead of crashing. Long-term, use prisma.user.upsert() or check with findUnique() before creating.
What does error.meta.target contain in P2002?+
error.meta.target is an array of the field names that caused the unique constraint violation — for example ['email'] or ['username', 'organizationId']. Use this to show specific error messages to users.
How do I use upsert to avoid P2002?+
Use prisma.model.upsert({ where: { email }, update: { ...data }, create: { ...data } }). This atomically inserts if not found or updates if found — no race conditions, no P2002.
P2002 on a field I didn't mark @unique — why?+
Check your schema for @@unique([fieldA, fieldB]) composite unique constraints. Also check if you have @id on the field — primary keys are implicitly unique. Run npx prisma studio to inspect the actual database constraints.
How do I find all unique constraints in my Prisma schema?+
Search your schema.prisma file for @unique and @@unique. Also check @id fields — they are implicitly unique. Run npx prisma db pull if your schema may be out of sync with the actual database.

Need Expert Help?

We Build Production-Grade Prisma Backends

Softplix architects and maintains Node.js backends with Prisma, PostgreSQL, and Next.js. Need a reliable data layer with proper error handling? Let us help.

Talk to an Engineer