sqlstreak

SQL error

insert or update violates foreign key constraint "orders_customer_id_fkey"

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

The row points to a parent row that doesn't exist: here an order for customer 12345, but there is no such customer. Insert the parent first, or reference an existing id.

The exact messages

  • PostgreSQLERROR: violates foreign key constraint "orders_customer_id_fkey"
  • SQLiteFOREIGN KEY constraint failed

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. DETAIL says more about what went wrong.

ERROR:  insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL:  Key (customer_id)=(12345) is not present in table "customers".

SQLite 3.54.1 reports the same mistake as FOREIGN KEY constraint failed, with no line number: look for the word or column it names.

Why it happens

Inserting a child before its parent

Insert customers before their orders, and orders before their order items.

Deleting a parent that still has children

The same error appears on DELETE. Delete children first, or declare the key with ON DELETE CASCADE if that's what you want.

SQLite only checks when asked

SQLite enforces foreign keys only after PRAGMA foreign_keys = ON; (it's on here).

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
INSERT INTO orders (id, customer_id, ordered_on, status)
VALUES (999, 12345, '2026-03-01', 'delivered');
Fixed
INSERT INTO orders (id, customer_id, ordered_on, status)
VALUES (999, 1, '2026-03-01', 'delivered');
SELECT id, customer_id, status FROM orders WHERE id = 999;

Customer 1 exists, so the order is accepted.

The fix returns, PostgreSQL: 1 row

idcustomer_idstatus
9991delivered

The fix returns, SQLite: 1 row

idcustomer_idstatus
9991delivered

Experiment with it: PostgreSQL playground·SQLite playground

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL CREATE TABLE, constraints and views.