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.
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.
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: "[email protected]",
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: "[email protected]"
// 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 devWhen 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: "[email protected]" } }),
prisma.user.create({ data: { email: "[email protected]" } })
]);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.
P6005: Invalid parameters (Pulse)
How to fix "P6005: Invalid parameters (Pulse)" in Prisma
P2009: Failed to validate the query: {validation_error}
How to fix "P2009: Failed to validate the query" in Prisma
P2007: Data validation error
How to fix "P2007: Data validation error" in Prisma
P1013: The provided database string is invalid
The provided database string is invalid
P1000: Authentication failed against database server
Authentication failed against database server