Prisma Error P2004: Constraint Failed on the Database

Prisma error P2004 (Constraint Failed on the Database) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

Error code P2004 Prisma Last verified 2026-08-19

Quick Answer

Read error.meta.database_error - the raw database message is the most specific clue. If that does not apply, look for CHECK/enum/exclude constraints in your schema or migrations that the value violates — the full checklist is below.

Error Code

Error code: P2004
Official name: Constraint Failed on the Database
Service: Prisma

What does this error mean?

A constraint failed on the database: {database_error}

Common Causes

How to Fix

  1. Read error.meta.database_error - the raw database message is the most specific clue
  2. Look for CHECK/enum/exclude constraints in your schema or migrations that the value violates
  3. If the error came from raw SQL ($queryRaw), verify the SQL against the actual column types
  4. Align the Prisma schema with the database: run prisma migrate dev after changing constraints

Code Examples

Surface the raw database error typescript
catch (e) {
  if (e.code === 'P2004') {
    console.error(e.meta.database_error)
  }
}

The wrapped database_error is the fastest path to the failing constraint.

Framework-Specific Fixes

nestjs

Fall back to a 400 for P2004 but keep the database_error text for developers.

if (e.code === 'P2004') {
  return response.status(400).json({
    message: 'Constraint violation',
    detail: e.meta.database_error,
  })
}
prisma-client

Use enum types and @db.* native types in the schema so invalid values fail validation before the DB round-trip.

model Order {
  status Status @default(PENDING)
}
enum Status { PENDING PAID CANCELLED }

You Might Also Like

Frequently Asked Questions

Why am I seeing Prisma error P2004?

Most often this happens when a database-level CHECK constraint rejecting a value (e.g. price > 0), or when an enum column receiving a value outside the declared enum.

How do I fix Prisma error P2004?

Read error.meta.database_error - the raw database message is the most specific clue.

Which frameworks have documented fixes for error P2004?

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.