Prisma Error P2003: Foreign Key Constraint Failed

Prisma error P2003 (Foreign Key Constraint Failed) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

Error code P2003 Prisma Last verified 2026-08-19

Quick Answer

Read error.meta.field_name to find the foreign key column that failed. If that does not apply, confirm the referenced parent record actually exists in the target table — the full checklist is below.

Error Code

Error code: P2003
Official name: Foreign Key Constraint Failed
Service: Prisma

What does this error mean?

Foreign key constraint failed on the field: {field_name}

Common Causes

How to Fix

  1. Read error.meta.field_name to find the foreign key column that failed
  2. Confirm the referenced parent record actually exists in the target table
  3. Check relation referential actions in the schema (onDelete: Restrict blocks parent deletes)
  4. Order writes correctly: create the parent before the child, or use nested create
  5. Look for mismatched ids (string vs number, wrong tenant/scope) feeding the foreign key

Code Examples

Nested create avoids FK errors typescript
const user = await prisma.user.create({
  data: {
    email: 'ada@example.com',
    profile: { create: { bio: 'Engineer' } },
  },
})

Prisma creates the parent first, then the dependent row, so the foreign key is always satisfied.

Inspect which FK field failed typescript
catch (e) {
  if (e.code === 'P2003') {
    console.error('foreign key:', e.meta.field_name)
  }
}

meta.field_name points at the offending column in the schema.

Framework-Specific Fixes

nestjs

Translate P2003 into HTTP 400/409 with the field name; tell clients the referenced parent is missing.

if (e.code === 'P2003') {
  return response.status(400).json({
    message: `Invalid reference on ${e.meta.field_name}`,
  })
}
prisma-client

Use nested creates so Prisma inserts the parent and child in one operation, satisfying the FK.

await prisma.user.create({
  data: {
    name: 'Ada',
    posts: { create: [{ title: 'Hello' }] },
  },
})

You Might Also Like

Frequently Asked Questions

Why am I seeing Prisma error P2003?

Most often this happens when inserting or updating a child row whose foreign key references a parent id that does not exist, or when deleting a parent row that is still referenced by children under a Restrict/NoAction relation.

How do I fix Prisma error P2003?

Read error.meta.field_name to find the foreign key column that failed.

Which frameworks have documented fixes for error P2003?

This page documents fixes for: nestjs, prisma-client.

Official Sources

This page is based on the official Prisma documentation linked below and adds practical troubleshooting guidance on top.