ERROR: insert or update on table "x" violates foreign key constraint "fk" — Key (user_id)=(5) is not present in table "users"

The row references a parent row that doesn’t exist.

Seen on: PostgreSQL

Meaning

The DETAIL line names the missing key. Inserting children before parents, deleted parents, or wrong ids from the client.

Common causes

  • Parent row doesn’t exist (wrong id)
  • Insert order wrong in seeds/imports
  • Parent deleted concurrently

⚡ Quick fix

  1. Insert parents first
  2. Validate the referenced id exists
  3. Defer constraints within a transaction for bulk loads (DEFERRABLE)

Detailed fix by platform

PostgreSQL

  1. SELECT 1 FROM users WHERE id = 5;

How to diagnose

  1. Key — DETAIL shows which key?
  2. Order — Parent inserted first?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.