skip to content

In Prisma 7 on PostgreSQL, deleting a User fails with P2003 because of their orders - which onDelete default caused it, and how do you change it?

level: seniorimportance: should knowfreq 45%

answer

  1. required versus optional relation
  2. the default nobody wrote
  3. Restrict, SetNull and Cascade
  4. a migration re-creates the foreign key
  5. P2003 names the constraint to read

basics

~20 s

With no onDelete, Prisma 7 gives a required relation Restrict and an optional one SetNull, so Order.user required means ON DELETE RESTRICT and the delete fails with P2003. Set onDelete on the Order side's @relation, then migrate.

solid answer

~40 s

When `@relation` names no referential action, Prisma applies defaults by optionality. A **required** relation such as `user User` with `userId Int` gets `onDelete: Restrict`, an **optional** one gets `SetNull`, and both get `onUpdate: Cascade`. Prisma Migrate writes these into the foreign key (`ON DELETE RESTRICT ON UPDATE CASCADE`), so PostgreSQL refuses to delete a user who still has orders, and Prisma Client surfaces that as `P2003`. To change it, set `onDelete` on the side holding the key, `Order.user`. `Cascade` deletes the orders too, `SetNull` keeps them with a NULL `userId` (the field must become optional), and `SetDefault` needs a `@default` on the scalar. Then create a migration, which drops and re-adds the constraint. For orders, keeping `Restrict` and anonymising the user is often the right answer. Implicit many-to-many tables always cascade.

go deeper

for a junior

Recall that onDelete and onUpdate live in @relation on the side with the foreign key, and that Prisma applies defaults when you write none.

for a middle

Explain the defaults, Restrict for required and SetNull for optional with onUpdate Cascade, and what each choice does to an order.

for a senior

Diagnose a P2003 on delete from the default, choose an action from business rules rather than to silence the error, and ship it as a migration.

for a principal

Set the deletion policy per relation from what the business must keep, such as order history, and decide where anonymising a user beats deleting one.

## Where the default comes from A **referential action** says what the database does to referencing rows when the referenced row is deleted (`onDelete`) or its key changes (`onUpdate`). In a Prisma schema you set both on the `@relation` attribute of the side that holds the foreign key. When you leave them out, Prisma ORM picks a default from the relation's **optionality**: | Clause | Optional relation (`User?`, `Int?`) | Required relation (`User`, `Int`) | | --- | --- | --- | | `onDelete` | `SetNull` | `Restrict` | | `onUpdate` | `Cascade` | `Cascade` | For a shop schema, Prisma 7.10's Migrate turns the defaults into concrete SQL: ```sql -- Order.user is required, no onDelete written ALTER TABLE "Order" ADD CONSTRAINT "Order_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; -- User.referredBy is optional, no onDelete written ALTER TABLE "User" ADD CONSTRAINT "User_referredById_fkey" FOREIGN KEY ("referredById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; ``` So `prisma.user.delete({ where: { id } })` on a user with orders hits `ON DELETE RESTRICT`. PostgreSQL rejects it, the PostgreSQL driver adapter maps the violation, and Prisma Client throws a `PrismaClientKnownRequestError` with code **`P2003`** (foreign key constraint failed). Nobody wrote `Restrict`; it came from `userId` being required. Deleting a referred user, by contrast, quietly nulls `referredById` on the users they referred. ## Choosing another action Edit the annotated side, `Order.user`, never the list side: ```prisma model Order { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id], onDelete: Cascade) userId Int } ``` The five values and what each costs in this schema: - **`Cascade`**: deleting the user deletes their orders, and any `OrderItem` rows declared `onDelete: Cascade` on their order side. Right for owned data such as a `Profile`; risky for orders, which accounting usually needs. - **`Restrict`**: the current default. Keep it when the application should decide, for example by anonymising the user instead of deleting them. - **`SetNull`**: orders survive with `userId` set to NULL, so `userId` must become `Int?` and `user` must become `User?`. On PostgreSQL, `prisma validate` only **warns** if you put `SetNull` on a required relation, and the delete then fails at runtime; other providers reject that schema outright. - **`SetDefault`**: needs `@default(...)` on the scalar field, pointing at a row that exists. - **`NoAction`**: close to `Restrict`; its exact difference depends on the database. Changing an action is a schema change. The next migration drops `Order_userId_fkey` and adds it again with the new clause, so it ships through your normal migration process. ## Where you cannot choose - **Implicit many-to-many relations** take no referential actions at all; validation fails with "Referential actions on implicit many-to-many relations are not supported". Their hidden join table cascades on both sides, so deleting a product silently unlinks it from every order. To choose, model the join explicitly and set `onDelete` per side. - **Explicit join models** get the same defaults as any required relation. Without an `onDelete`, `OrderItem.product` is `Restrict`, which is often what you want: a product that was sold cannot be deleted. ## When the database does not enforce the action Everything above assumes Prisma's default `relationMode`, `foreignKeys`, where the action lives in the foreign key and the database carries it out for every writer. Under `relationMode = "prisma"` there is no foreign key and Prisma Client emulates the actions itself; whether to accept that is a separate decision with its own costs. ## A diagnosis checklist When a delete fails with `P2003`, read the constraint the error names and check its model's `@relation`. If no `onDelete` is written, apply the table above. Then decide what the business wants, and only after that pick the action and migrate. Reaching for `Cascade` just to make the error go away is how order history disappears.

  • Why does Prisma only warn about SetNull on a required relation for PostgreSQL?
    PostgreSQL is the one supported database that lets you declare `ON DELETE SET NULL` on a non-nullable column; the error appears only when the action fires. Prisma therefore accepts the schema with a warning recommending another action or optional fields. Other providers reject it at validation time. Either way the fix is the same: make `userId` and `user` optional, or choose another action.
  • What does the default onUpdate: Cascade do here, and when does it matter?
    If a user's `id` changes, PostgreSQL rewrites every `Order.userId` that pointed at it in the same statement. With an autoincrement `id` that almost never happens, so the default is harmless. It matters when the referenced field is a natural key that can change, such as an email or a SKU marked `@unique`. Set `onUpdate: Restrict` when such a change should be refused rather than spread.

  • Prisma's default onDelete is always Cascade, like most ORMs.
  • onDelete belongs on the list side, such as orders Order[] on User.
  • SetNull works on a required userId; Prisma makes it nullable automatically.
  • Changing onDelete takes effect without a migration because Prisma Client enforces it.
  • An implicit many-to-many accepts onDelete: Restrict to protect its rows.