# Postgres error 23503: insert or update on table "x" violates foreign key constraint "x_y_fkey"

> A row points at a parent that does not exist, or a delete would leave children pointing at nothing.

Source: https://scribase.com/postgres-errors/23503

SQLSTATE class: Integrity Constraint Violation. Over PostgREST/supabase-js this maps to HTTP 409.

## Causes

- Inserting a child before its parent, or with a wrong parent id.
- Deleting a parent row that still has children, when the foreign key is ON DELETE NO ACTION or RESTRICT.
- Loading tables in the wrong order during a migration or restore.

## Fixes

- Insert parents first, or insert both in one transaction with the constraint DEFERRABLE INITIALLY DEFERRED.
- Decide what deleting a parent should do: ON DELETE CASCADE, SET NULL, or keep it restricted and delete children explicitly.
- During bulk loads, add foreign keys after the data.

## Example

```sql
alter table comments drop constraint comments_post_id_fkey,
  add constraint comments_post_id_fkey foreign key (post_id) references posts (id) on delete cascade;
```

PostgREST answers 409 Conflict. The details field names the missing key.