Foreign key violation caused by insert order or circular references
Rows must be inserted parent-first, and two tables that reference each other need deferred constraints or nullable columns.
foreign key constraint fails circular referenceinsert order foreign key violationcircular foreign key dependencyDEFERRABLE INITIALLY DEFERREDcannot insert because parent key not found bulk load Meaning
Insert the referenced rows before referencing ones, delete in reverse order, and for circular references (employee↔department, A↔B) insert one side with NULL, then update, or use DEFERRABLE INITIALLY DEFERRED (PostgreSQL/Oracle) so checks happen at COMMIT.
Common causes
- Child inserted before the parent
- Bulk load order not respecting FKs
- Circular foreign keys between two tables
- Deleting parents before children
- ORM batch flush order
⚡ Quick fix
- Load/insert parents first, delete children first
- Use deferrable constraints for circular references
- Insert with NULL then update the FK
Detailed fix by platform
SQL
ALTER TABLE a ADD CONSTRAINT fk_b FOREIGN KEY (b_id) REFERENCES b(id) DEFERRABLE INITIALLY DEFERRED;
How to diagnose
- Insert order — Parent first?
- Circular FK — Present?
- Deferrable — Available?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in SQL
Other ways to find it
Where this error sits
Origin: Data. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 18 Nov 2026