Prisma error P2003: Foreign key constraint failed on the field

Prisma·Sep 12, 2026·intermediate·
Quick answer

You're trying to create or update a record that references a foreign key ID which doesn't exist in the related table — for example, creating an Article with a `pillarId` that doesn't match any real Pillar. Verify the referenced ID actually exists before the write, or handle the error to show a clear message.

What causes this error

Every relation field backed by a foreign key (like Article.pillarId referencing Pillar.id) requires the referenced row to actually exist. P2003 fires when you try to insert or update a record pointing at an ID that isn't there — a stale reference, a typo, or a race condition where the related record was deleted first.

The Fix

try {
  await prisma.article.create({ data: { pillarId, ...rest } });
} catch (err) {
  if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2003') {
    throw new ApiError(400, 'The selected pillar no longer exists — refresh and try again');
  }
  throw err;
}

Common causes / variations

  • A frontend form holding a stale pillar/tag ID after it was deleted elsewhere
  • Seeding data in the wrong order — creating child records before their parent exists
  • A race condition where two requests delete and reference the same row nearly simultaneously

Related errors

See also: P2002 Unique constraint failed, P2025 Record not found.

Was this fix helpful?

Comments

Loading comments...