Circular References
Go Up to Defining Integrity Constraints on a Table
When two tables reference each other’s foreign keys and primary keys, a circular reference exists between the two tables. In the following illustration, the foreign key in the EMPLOYEE table, DEPT_NO, references the primary key, DEPT_NO, in the DEPARTMENT table. Therefore, the primary key, DEPT_NO must be defined in the DEPARTMENT table before it can be referenced by a foreign key in the EMPLOYEE table. In the same manner, EMP_NO, which is the primary key of the EMPLOYEE table, must be created before the DEPARTMENT table can define EMP_NO as its foreign key.
The problem with circular referencing occurs when you try to insert a new row into either table. Inserting a new row into the EMPLOYEE table causes a new value to be inserted into the DEPT_NO (foreign key) column, but you cannot insert a value into the foreign key column unless that value already exists in the DEPT_NO (primary key) column of the DEPARTMENT table. It is also true that you cannot add a new row to the DEPARTMENT table unless the values placed in the EMP_NO (foreign key) column already exist in the EMP_NO (primary key) column of the EMPLOYEE table. Therefore, you are in a deadlock situation because you cannot add a new row to either table!
InterBase gets around the problem of circular referencing by allowing you to insert a NULL value into a foreign key column before the corresponding primary key value exists. The following example illustrates the sequence for inserting a new row into each table:
- Insert a new row into the
EMPLOYEEtable by placing “1” in theEMP_NOprimary key column, and aNULLin theDEPT_NOforeign key column. - Insert a new row into the
DEPARTMENTtable, placing “2” in theDEPT_NOprimary key column, and “1” in the foreign key column. - Use
ALTER TABLEto modify theEMPLOYEEtable. Change theDEPT_NOcolumn fromNULLto “2.”