# insert or update violates foreign key constraint "orders_customer_id_fkey"

Source: https://sqlstreak.com/sql/errors/violates-foreign-key-constraint · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

- PostgreSQL: `ERROR: violates foreign key constraint "orders_customer_id_fkey"`
- SQLite: `FOREIGN KEY constraint failed`

## How PostgreSQL prints it

```
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".
```

## 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).

## The broken query

```sql
INSERT INTO orders (id, customer_id, ordered_on, status)
VALUES (999, 12345, '2026-03-01', 'delivered');
```

## The fix

```sql
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.

| id | customer_id | status |
| --- | --- | --- |
| 999 | 1 | delivered |
