How to fix P2011: Null constraint violation on the field in Prisma

PrismaBEGINNERMEDIUMUpdated Dec 29, 2025ยท 135 views

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
}
  1. Check your Prisma schema for required fields
  2. Ensure all required fields are provided in create operations
  3. Configure proper default values for auto-generated fields
  4. Verify schema matches your database
prisma โ€” error
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
}
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

  1. Missing required field value in create or update data object
  2. Field is required in the database but marked as optional in Prisma schema
  3. Default value function (@default) is not working or misconfigured
  4. Database default value exists but Prisma expects a provided value
  5. PostgreSQL custom domain with NOT NULL constraint not being handled correctly
  6. Schema drift: Prisma schema does not match actual database constraints
  7. Auto-generated ID field (UUID or autoincrement) is null due to misconfiguration
  8. Attempting to update a required field to null or with empty data

How to fix "P2011: Null constraint violation on the field"

1Check your Prisma schema for required fields

Review your model definition to identify which fields are required (non-nullable). By default, all fields in Prisma are non-nullable:

prisma
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.

2Ensure all required fields are provided in create operations

When creating a record, explicitly provide values for all required fields:

typescript
// 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.

3Configure proper default values for auto-generated fields

For fields that should be automatically generated, use Prisma's @default() function:

prisma
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:

typescript
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.

4Verify schema matches your database

Use Prisma's introspection to detect schema drift between your Prisma schema and actual database constraints:

bash
npx prisma db pull

This command introspects your database and updates your schema.prisma file. Review the changes:

bash
git diff prisma/schema.prisma

If 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

5Handle optional fields correctly

To make a field optional (nullable), add a question mark (?) in your Prisma schema:

prisma
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:

typescript
const user = await prisma.user.create({
  data: {
    email: "john@example.com"
    // phone and nickname are not required
  }
});
6Add validation before creating records

Validate data before passing it to Prisma to catch missing required fields early:

typescript
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.

7Catch and handle P2011 errors in your code

Add error handling to gracefully handle P2011 errors:

typescript
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;
}
8Check for database-specific issues with custom domains

If you're using PostgreSQL custom domains or native types, the error message may not specify which field caused the issue:

bash
# Error message shows empty brackets
P2011: Null constraint violation on the fields: ()

For PostgreSQL, verify custom domain nullability:

sql
-- 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:

bash
npx prisma migrate dev

Advanced 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:

typescript
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