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.
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: P2004
Official name: Constraint Failed on the Database
Service: Prisma
A constraint failed on the database: {database_error}
catch (e) {
if (e.code === 'P2004') {
console.error(e.meta.database_error)
}
}
The wrapped database_error is the fastest path to the failing constraint.
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,
})
}
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 }
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.
Read error.meta.database_error - the raw database message is the most specific clue.
This page documents fixes for: nestjs, prisma-client.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official Prisma documentation linked below and adds practical troubleshooting guidance on top.