What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
You cannot insert either row first when each row immediately needs the other to exist. The solution depends on the database: PostgreSQL and Oracle document deferrable foreign-key checks; MySQL InnoDB checks immediately, so use a valid nullable-reference workflow or reconsider the schema instead.
Why the first insert fails
A foreign key requires every non-null value in a referencing column to match a key in the referenced table. If row A references row B and row B references row A, each insert depends on a row that has not yet been created. With immediate checking, the database rejects whichever row you try to insert first. This is an insertion-order problem caused by constraint timing, not proof that the relationship cannot be modeled. See the PostgreSQL 18 constraints documentation.
Putting both inserts inside a transaction does not, by itself, postpone foreign-key validation. The constraints must support and be configured for deferral, or the insert sequence and schema must allow a valid intermediate state.
Choose a method that fits your database and data rules
| Approach | When it fits | Important limitation |
|---|---|---|
| Defer foreign-key checks | The database supports deferrable constraints and the relevant constraints are declared deferrable. | Not available for every engine or storage engine; validation still must succeed by the time it occurs. |
| Insert with a temporary NULL, then update | The foreign-key column may validly be NULL during the operation. | Does not suit a relationship that must be non-null in every intermediate state. |
| Use a self-reference | The relationship is a single row referring to itself, and that meaning is valid in the application. | Not a general solution for cycles across multiple tables, and behavior should be checked for the database. |
| Redesign the relationship or loading process | Checks cannot be deferred and a temporary NULL is invalid or unavailable. | Requires preserving and validating the final integrity rules; disabling checks is not equivalent to enforcing them. |
PostgreSQL: declare the foreign keys deferrable
PostgreSQL 18 supports foreign keys declared DEFERRABLE. The default is NOT DEFERRABLE, so an ordinary foreign key will not become deferred merely because inserts run in a transaction. The PostgreSQL 18 CREATE TABLE documentation describes the constraint options.
#1 Best Overall
For example, the relevant constraints can be declared with the following pattern (adapt table, column, and key names to your schema):
CREATE TABLE a (
id integer PRIMARY KEY,
b_id integer REFERENCES b(id) DEFERRABLE
);
CREATE TABLE b (
id integer PRIMARY KEY,
a_id integer REFERENCES a(id) DEFERRABLE
);
Then insert both rows in one transaction and defer the checks until the transaction is ready to 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;
The key point is that the constraints must be deferrable. At commit, PostgreSQL checks that the referenced rows exist. If the completed state still violates a foreign key, the transaction cannot commit successfully.
Oracle: defer the constraints in the transaction
Oracle Database 26 documents deferrable constraints and the transaction command SET CONSTRAINTS ALL DEFERRED. Declare the relevant constraints as deferrable, insert the mutually dependent rows in one transaction, and defer their checks so the database can validate the completed state. The Oracle Database 26 data-integrity documentation covers this behavior.
As with PostgreSQL, deferral changes when validation happens; it does not remove the foreign-key requirement. The references must be valid when the deferred check is performed.
MySQL: distinguish InnoDB from NDB
For MySQL 8.4 InnoDB, foreign-key checks are immediate. Wrapping the two inserts in a transaction does not defer them until commit, so a circular pair cannot be inserted by relying on transaction boundaries alone. MySQL treats NO ACTION as RESTRICT for foreign keys; it is not a way to postpone validation.
Rank #4
MySQL NDB is a documented exception that supports deferred checks. Confirm the storage engine used by the tables before choosing an approach. The MySQL 8.4 foreign-key documentation describes the engine distinctions.
Free tools Windows power users keep installed
One-click scans. No signup required.
When a temporary NULL is a valid bridge
If the relationship is allowed to be absent temporarily, create one row with a NULL foreign key, insert the related row, and then update the first row to point to it. For example, if A can temporarily exist without its reference to B, the sequence is:
Best Value
- Insert A with its B foreign-key column set to NULL.
- Insert B with its reference to A set to A’s key.
- Update A so its B foreign-key column contains B’s key.
- Commit after the final references are valid.
This works only if the column permits NULL and the application accepts that intermediate state. If the relationship is mandatory at all times, making it nullable merely to get past the insert may violate the domain’s rules. Oracle’s documentation discusses nullable references in the context of creating an initial row.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Self-referencing rows are a separate case
A row that refers to itself can sometimes be inserted by using the same known key for the row and its referenced value. Oracle documents an employee/manager example in which the first row has equal employee and manager IDs because constraint checking follows the statement. This is appropriate only if self-reference has a valid meaning in the application. Do not assume this resolves a cycle involving multiple tables or that another database behaves the same way; consult that engine’s documentation. See Oracle’s data-integrity guidance.
SQL Server and other engines: do not assume deferral
The SQL Server 2022 documentation consulted describes foreign-key enforcement and cascading referential actions, but does not document deferred foreign-key checking. Do not apply PostgreSQL or Oracle deferral syntax to SQL Server on that basis. If checks are immediate, consider a nullable bridge only when the application permits it, or redesign the relationship or controlled load process. Microsoft’s SQL Server primary and foreign key documentation explains its documented constraint behavior.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →If neither deferral nor a nullable bridge works
- Make one relationship optional if the domain allows one side to be absent, rather than forcing both references to be present at creation.
- Represent the association separately when a dedicated relationship table better reflects the actual model and its creation sequence.
- Use a controlled bulk-load process only if the database and operational process allow constraints to be applied or validated after loading. Confirm the final data against the intended integrity rules; a period with checks disabled is not the same as continuous enforcement.
Choose based on the actual database and storage engine, whether constraints are declared deferrable, whether NULL is valid in the domain, and whether the cycle is self-referential or spans tables. The database-specific behavior above is documented by the cited vendors; the right schema choice depends on the application’s invariants.
Quick Recap
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.

