FluentDBFluentDB
PostgreSQL errors

PostgreSQL: update or delete violates a foreign key on another table

ERRORSQLSTATE 23503foreign_key_violation
ERROR: update or delete on table "<parent>" violates foreign key constraint "<fk>" on table "<child>"

You tried to delete or update a parent row that child rows still reference. Delete or reassign the children first, or define ON DELETE CASCADE or SET NULL so Postgres handles them.

What this error means

This is the delete side of a foreign key. A child table still has rows pointing at the parent row you are removing or changing, and the constraint blocks it to avoid orphaned references. The DETAIL names the still-referencing table.

How to fix it

01

Children still reference the parent

Delete or reassign the child rows first.

sql
DELETE FROM order_items WHERE order_id = 42;
DELETE FROM orders WHERE id = 42;
02

You want deletes to cascade

Define the foreign key with ON DELETE CASCADE (or SET NULL) so children are handled automatically.

sql
ALTER TABLE order_items
  DROP CONSTRAINT order_items_order_id_fkey,
  ADD CONSTRAINT order_items_order_id_fkey
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE;
03

You should not hard-delete

Consider a soft delete (a deleted_at column) when the row is referenced widely.

How to avoid it next time

  • Choose ON DELETE behavior deliberately when you define each foreign key.
  • Know which tables reference a row before you delete it.

Frequently asked questions

How is this different from an insert foreign key violation?

The insert case means a child points to a missing parent. This case means you are removing a parent that children still reference.

What does ON DELETE CASCADE do?

It automatically deletes the child rows when the parent is deleted, so you do not have to remove them by hand.

Stop struggling with SQL

Use FluentDB, the AI database client for macOS.