Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

Circular Foreign Keys: How to Insert Mutually Dependent Rows

Mutually dependent rows can fail under immediate foreign-key checks. The workaround depends on the database, constraint definition, and whether a temporary NULL is valid.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When two new rows each reference the other, an immediate foreign-key check rejects whichever row you try to insert first: its referenced row does not exist yet. The fix depends on your database and schema. PostgreSQL and Oracle document deferrable constraints that can be checked at transaction end; MySQL InnoDB checks immediately, so a transaction alone does not solve the cycle.

Why a circular foreign key blocks the first insert

A foreign key protects referential integrity: every non-null value in a referencing column must match an existing key in the referenced table. If row A points to row B and row B points to row A, inserting either one first creates a reference to a row that is not yet present. With immediate checking, the database rejects that insert.

As an Amazon Associate I earn from qualifying purchases.

The problem is the timing of validation combined with the dependency between rows. A circular relationship is not inherently impossible to model; the completed pair can satisfy both constraints. The challenge is getting to that valid final state without violating a constraint along the way. See the PostgreSQL 18 constraints documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a method that fits the database and the relationship

  • Use deferred constraints when the database supports them and the relevant constraints are declared deferrable. Both rows can be inserted in one transaction and checked after the pair exists.
  • Use a temporary NULL reference when the relationship is genuinely allowed to be absent during creation. Insert one row without its reference, create the other row, then update the first.
  • For a self-reference, use a row that refers to itself only if that meaning is valid in the application and the engine’s documented behavior supports it.
  • Change the schema or loading process if none of those options preserves the application’s rules. A nullable relationship, a separate association table, or a controlled bulk-load process may fit, but final data still needs validation.

How constraint timing differs by database

Database Documented behavior What it means for this insert cycle
PostgreSQL 18 Foreign keys can be declared DEFERRABLE; NOT DEFERRABLE is the default. A deferrable constraint can be postponed until transaction end. Declare the relevant foreign keys deferrable, then defer them in the transaction before inserting the mutually dependent rows.
Oracle Database 26 Deferrable constraints can be deferred with SET CONSTRAINTS ALL DEFERRED. Oracle also documents first-row cases for self-referencing constraints. Use deferred checks for a multi-row cycle when the constraints are configured to allow deferral; treat self-reference as a separate, documented case.
MySQL 8.4 InnoDB Foreign-key checks are immediate; NO ACTION is treated as RESTRICT. MySQL NDB is an exception that supports deferred checks. A transaction does not defer InnoDB foreign-key checks. Do not assume NDB behavior applies to InnoDB.
SQL Server 2022 documentation consulted The cited documentation describes foreign-key enforcement and cascading referential actions, but does not document deferred checking. Do not assume deferred-constraint syntax from the cited documentation. Consider a valid nullable bridge or a schema/load redesign instead.

Sources: PostgreSQL 18 CREATE TABLE, Oracle Database 26 data integrity, MySQL 8.4 foreign-key constraints, and Microsoft’s SQL Server 2022 documentation.

Using deferred constraints in PostgreSQL

Both foreign keys involved in the cycle must be declared DEFERRABLE. For example, the schema can define the references this way:

CREATE TABLE a (
  id integer PRIMARY KEY,
  b_id integer REFERENCES b(id) DEFERRABLE INITIALLY IMMEDIATE
);

CREATE TABLE b (
  id integer PRIMARY KEY,
  a_id integer REFERENCES a(id) DEFERRABLE INITIALLY IMMEDIATE
);

With those constraints in place, defer checking inside the transaction, insert both rows, and commit:

BEGIN;
SET CONSTRAINTS ALL DEFERRED;

INSERT INTO a (id, b_id) VALUES (1, 2);
INSERT INTO b (id, a_id) VALUES (2, 1);

COMMIT;

At commit, PostgreSQL checks that the references resolve. If the rows do not form a valid final state, the transaction cannot commit successfully. A transaction by itself is not enough: constraints declared NOT DEFERRABLE remain immediate. PostgreSQL documents the syntax and default in its CREATE TABLE reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using deferred constraints in Oracle

Oracle also supports deferrable constraints. Configure the relevant constraints as deferrable in the schema, then defer checking for the transaction with SET CONSTRAINTS ALL DEFERRED. Insert both mutually dependent rows before committing, so the database can validate the completed state.

Oracle’s documentation also describes an initial self-referencing row, such as an employee row whose manager ID equals that employee’s ID. That example concerns a row referring to itself; it should not be treated as proof that every multi-table cycle can be inserted under immediate checking. See Oracle Database 26: Maintaining Data Integrity in Database Applications.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When a nullable bridge is appropriate

If the application permits the relationship to be temporarily absent, create one row with a NULL foreign-key value, insert the dependent row, then update the first row to point to it. This works only when the column allows NULL and the domain permits that intermediate state. It is not appropriate when the relationship must be present at every point in the data lifecycle.

Rank #4
SQL Database Query Programmer T-Shirt
  • Database Programming design. Funny database SQL joke that makes a great gift for database administrators, programmers or computer scientists. Fun gift for database administrators, programmers and hackers who like to wear funny nerd clothes.
  • Funny gift for men and women who love SQL. The perfect SQL Query top for programmers, hackers and SQL database fans who love relational databases.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

When to redesign the relationship or load process

If the database cannot defer the relevant checks and a temporary NULL would violate the domain, revisit the model rather than trying random insert orders. Possible designs include making one relationship optional if that reflects reality, moving the association into a separate table, or using a controlled bulk-load procedure followed by explicit validation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Disabling or bypassing checks is not equivalent to enforcing referential integrity. Any loading process that postpones enforcement must still establish that all references are valid before the data is treated as complete. The right choice depends on whether deferral is supported by the deployed database and storage engine, whether NULL is semantically allowed, and whether the relationship is self-referential or spans multiple tables.

Quick Recap

SaleBestseller No. 1
Bestseller No. 4
SQL Database Query Programmer T-Shirt
SQL Database Query Programmer T-Shirt
Lightweight, Classic fit, Double-needle sleeve and bottom hem
$19.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.