Skip to main content
AllDevToolsHub
Back to error codes
ERROR 23503

PostgreSQL Foreign Key Violation

Database Error

An INSERT or UPDATE references a value that does not exist in the referenced table.

Root Cause

Trying to insert a row with a foreign key value that does not exist in the parent table, or deleting a parent row that has child rows.

How to Fix

Ensure the referenced row exists before inserting. Use ON DELETE CASCADE or ON DELETE SET NULL to handle parent row deletions.

Quick Summary

PostgreSQL error 23503: foreign key violation. The referenced row does not exist. Ensure parent rows exist before inserting child rows. Use ON DELETE CASCADE for automatic cleanup.

Key Takeaways

Key Takeaways

  • Error code 23503 = foreign_key_violation in PostgreSQL
  • The referenced row in the parent table does not exist
  • Use ON DELETE CASCADE to automatically delete child rows when a parent is deleted
  • Use ON DELETE SET NULL to set the foreign key to NULL when the parent is deleted
Use Cases

When to use it

  • Inserting an order for a non-existent user
  • Deleting a user who has orders
  • Referencing a category that was deleted
Watch out

Common Mistakes

  • Not using ON DELETE CASCADE when child rows should be deleted with the parent
  • Not handling the error gracefully, return a meaningful error message to the client
FAQ

23503 PostgreSQL Foreign Key Violation, Frequently Asked

How do I delete a parent row that has child rows?

Either delete child rows first, use ON DELETE CASCADE in the schema, or use ON DELETE SET NULL to nullify the foreign key.

Still having issues?

Check your network logs or use our developer tools to inspect headers, decode tokens, or validate your requests.