When are circular references acceptable in database?
Theoretical and practical, any help is appreciated.
Circular references aren't a bad thing in itself: you can use them to achieve complex calculations that are otherwise impossible to do, but first you must set them up properly.
In the world of relational databases circular references are schema structures where foreign keys relating the tables create a loop. Circular references cause special types of issues when trying to synchronize two relational database where the foreign keys are enforced.
Circular Dependency : Here when we try to delete a record from TABLE A, it throws an error message as Column P & Column R of TABLE B are depending on Column Q of TABLE A. When we try to delete a record from TABLE B, it again throws an error message as Column P of TABLE A is depending on Column P of TABLE B.
A circular reference occurs when one heap variable contains a reference to a second heap variable, and the second one contains a reference back to the first. For instance, if A is an object, and somewhere in A, there is a reference to B, and within B is a reference back to A, there is a circular reference.
Consider cities and states. Each city exists within a state. Each state has a capital city.
CREATE TABLE city ( city VARCHAR(32), state VARCHAR(32) NOT NULL, PRIMARY KEY (city), FOREIGN KEY (state) REFERENCES state (state) ); CREATE TABLE state ( state VARCHAR(32), capital_city VARCHAR(32), PRIMARY KEY (state), FOREIGN KEY (capital_city) REFERENCES city (city) );
First problem - You cannot create these tables as shown, because a foreign key can't reference a column in a table that doesn't (yet) exist. The solution is to create them without the foreign keys, and then add the foreign keys afterwards.
Second problem - you cannot insert rows into either table, as each insert will require a pre-existing row in the other table. The solution is to set one of the foreign key columns to be NULL, and insert that data in two phases. e.g.
--Create state record INSERT INTO state (state, capital_city) VALUES ('Florida', NULL); --Create various city records INSERT INTO city (city, state) VALUES ('Miami', 'Florida'); INSERT INTO city (city, state) VALUES ('Tallahassee', 'Florida'); INSERT INTO city (city, state) VALUES ('Orlando', 'Florida'); --Set one of the cities as the capital UPDATE state SET capital_city = 'Tallahassee' WHERE state = 'Florida';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With