SQLSTATE 23503Severity lowLab verified

Incident brief

Insert or update violates foreign key constraint

A row referenced a value in another table through a FOREIGN KEY, but that value doesn't exist there. PostgreSQL rejects the row to keep the two tables consistent.

What lands in your log

ERROR: insert or update on table "order_items" violates foreign key constraint "order_items_order_id_fkey"

Reproduced on PostgreSQL 16.14Verified 2026-07-15 (Docker lab, PostgreSQL 16.14)Verified against PostgreSQL 16.14 in an isolated lab environment

In 10 seconds

What triggers it
Create a parent table and a child table with a FOREIGN KEY referencing the parent.
Fix
Insert the parent row first, then the child row that references it.
Proof
Reproduced on PostgreSQL 16.14 → The INSERT referencing a non-existent parent id (999) was rejected with SQLSTATE 23503 and the row was never stored.

Fix

What to do right now

Application-level steps for this error.

  • Insert the parent row first, then the child row that references it.
  • Double-check the referenced id actually exists before inserting.
  • Decide an ON DELETE policy (CASCADE, RESTRICT, SET NULL) up front so parent deletes behave the way you expect.
Fix SQL
-- Parent first, then child, tables already exist from setup.
INSERT INTO shop.orders (id) VALUES (1);
INSERT INTO shop.order_items (id, order_id) VALUES (1, 1);
SELECT * FROM shop.order_items;

Runbook to fix this

The runbook for this incident

Full step-by-step fixes for the condition behind this error: the diagnosis, the exact SQL, and output captured in the lab.

Verification

PG 16.14
Last verified
2026-07-15 (Docker lab, PostgreSQL 16.14)
Verification scope
Verified against PostgreSQL 16.14 in an isolated lab environment
Audit status
reviewed
ShareLinkedInX

Went further?

Pro unlocks the second lab proof

Free page stops the bleeding. Pro adds the operational test, SQLSTATE audit, and deeper evidence, same error, more certainty.

FollowSubstackLinkedInnew errors · lab notes · hiring loops