How to fix P2011: Null constraint violation on the field in Prisma
This error occurs when you try to create or update a record without providing a required value for a non-nullable field. Ensure all required fields in your Prisma model have values before saving, check that default values are properly configured, and verify your schema matches your database constraints.
Quick fix
Fixes P2011: Null constraint violation on the field
model User {
id String @id @default(cuid()) // Required: must have a default or be provided
email String // Required: must be provided
name String? // Optional: can be null
age Int? // Optional: can be null
}- Check your Prisma schema for required fields
- Ensure all required fields are provided in create operations
- Configure proper default values for auto-generated fields
- Verify schema matches your database
model User {id String @id @default(cuid()) // Required: must have a default or be providedemail String // Required: must be providedname String? // Optional: can be nullage Int? // Optional: can be null}P2011: Null constraint violation on the field
What this error means
The P2011 error in Prisma means you're attempting to create or update a database record without providing a value for a field that cannot be NULL. In Prisma, all fields are non-nullable by default unless explicitly marked with a question mark (?). This error is enforced by your database to maintain data integrity. For example, if your User model has a required `email` field and you try to create a user without providing an email, Prisma will throw P2011.
Typical symptoms
- Prisma throws "P2011: Null constraint violation on the field: {fieldName}"
- Error occurs when creating new records with .create()
- Error occurs when updating records with .update()
- The error message may show empty brackets () if caused by a PostgreSQL custom domain
- Error only happens with certain operations, not consistently
- Database constraints appear to be violated even though you think you provided values
Common causes
- Missing required field value in create or update data object
- Field is required in the database but marked as optional in Prisma schema
- Default value function (@default) is not working or misconfigured
- Database default value exists but Prisma expects a provided value
- PostgreSQL custom domain with NOT NULL constraint not being handled correctly
- Schema drift: Prisma schema does not match actual database constraints
- Auto-generated ID field (UUID or autoincrement) is null due to misconfiguration
- Attempting to update a required field to null or with empty data
How to fix "P2011: Null constraint violation on the field"
Review your model definition to identify which fields are required (non-nullable). By default, all fields in Prisma are non-nullable:
model User {
id String @id @default(cuid()) // Required: must have a default or be provided
email String // Required: must be provided
name String? // Optional: can be null
age Int? // Optional: can be null
}In this schema, id and email are required. When creating a User, you must provide an email value. The id will be auto-generated by the @default(cuid()) function, but you must still provide email.
When creating a record, explicitly provide values for all required fields:
// WRONG - missing required email field
const user = await prisma.user.create({
data: {
name: "John Doe"
}
});
// CORRECT - providing required email field
const user = await prisma.user.create({
data: {
email: "john@example.com",
name: "John Doe"
}
});The error message should tell you which field is causing the issue. If the error shows empty brackets (), check your database for custom domains or constraints.
For fields that should be automatically generated, use Prisma's @default() function:
model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
published Boolean @default(false)
title String
}When creating a Post, you don't need to provide id, createdAt, or published because they have defaults:
const post = await prisma.post.create({
data: {
title: "My First Post"
// id, createdAt, and published are auto-generated
}
});For integer IDs, use @default(autoincrement()) in PostgreSQL or @default(uuid()) for UUIDs.
Use Prisma's introspection to detect schema drift between your Prisma schema and actual database constraints:
npx prisma db pullThis command introspects your database and updates your schema.prisma file. Review the changes:
git diff prisma/schema.prismaIf there are differences in nullability or constraints, either:
1. Accept the database schema: git add prisma/schema.prisma && npm run build
2. Or migrate the database to match your schema: npx prisma db push
To make a field optional (nullable), add a question mark (?) in your Prisma schema:
model User {
id String @id @default(cuid())
email String
phone String? // Optional: can be null
nickname String? // Optional: can be null
}Now you can create a User without providing phone or nickname:
const user = await prisma.user.create({
data: {
email: "john@example.com"
// phone and nickname are not required
}
});Validate data before passing it to Prisma to catch missing required fields early:
import { z } from 'zod';
const userSchema = z.object({
email: z.string().email(),
name: z.string().min(1),
age: z.number().optional()
});
const data = { name: "John" }; // Missing email
try {
const validatedData = userSchema.parse(data);
const user = await prisma.user.create({ data: validatedData });
} catch (error) {
if (error instanceof z.ZodError) {
console.error("Validation failed:", error.errors);
}
}This catches the missing email field before it reaches Prisma.
Add error handling to gracefully handle P2011 errors:
import { Prisma } from '@prisma/client';
try {
const user = await prisma.user.create({
data: {
email: userInput.email,
name: userInput.name
}
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2011') {
console.error("Null constraint violation:", error.message);
// Return user-friendly error message
throw new Error(
`Cannot create record: missing required field. Check that all required fields have values.`
);
}
}
throw error;
}If you're using PostgreSQL custom domains or native types, the error message may not specify which field caused the issue:
# Error message shows empty brackets
P2011: Null constraint violation on the fields: ()For PostgreSQL, verify custom domain nullability:
-- Check your custom domain definition
SELECT typname, typnotnull FROM pg_type WHERE typname = 'your_domain';If typnotnull is true, the domain is NOT NULL. Ensure your Prisma field does not have @db.UnsignedBigInt() or other native types with built-in constraints that conflict with your schema definition.
Run migrations to sync the database:
npx prisma migrate devAdvanced notes
When using Prisma with managed services like PlanetScale, the error may only occur in production but not locally due to database configuration differences. Always test with the same database version and constraints as your production environment.
For auto-generated ID fields, ensure the database trigger or default value is properly configured. With UUID fields, use @default(uuid()) in Prisma and @db.Uuid in PostgreSQL. With autoincrement, use @default(autoincrement()) and ensure the sequence is created.
When using createMany() for batch inserts, if any record violates a null constraint, the entire batch fails. Use transactions to handle partial failures:
await prisma.$transaction([
prisma.user.create({ data: { email: "a@example.com" } }),
prisma.user.create({ data: { email: "b@example.com" } })
]);For relations, ensure you're using the correct relation field. When a relation is required, you must either provide the id or use connect/create nested operations.
Frequently asked questions
- What does "P2011: Null constraint violation on the field" mean?
- The P2011 error in Prisma means you're attempting to create or update a database record without providing a value for a field that cannot be NULL. ). This error is enforced by your database to maintain data integrity.
- How do I fix "P2011: Null constraint violation on the field"?
- This error occurs when you try to create or update a record without providing a required value for a non-nullable field. Ensure all required fields in your Prisma model have values before saving, check that default values are properly configured, and verify your schema matches your database constraints.
- What causes "P2011: Null constraint violation on the field"?
- Missing required field value in create or update data object Field is required in the database but marked as optional in Prisma schema Default value function (@default) is not working or misconfigured
- Is the "P2011: Null constraint violation on the field" error serious?
- It is a medium-severity error โ more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- ๐Prisma Official Documentation
- ๐prisma.io - error reference(Official Docs)
- ๐prisma.io - models(Official Docs)
- ๐prisma.io - correctness constraints(Official Docs)
- ๐github.com - 21053(GitHub)
- ๐github.com - 666(GitHub)