Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are circular references acceptable in database?

When are circular references acceptable in database?

Theoretical and practical, any help is appreciated.

like image 520
yli Avatar asked Jun 17 '09 13:06

yli


People also ask

Is it okay to have circular references?

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.

What is circular references in database?

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.

What is circular dependency in SQL?

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.

What is a circular reference in programming?

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.


1 Answers

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'; 
like image 164
fisharebest Avatar answered Sep 20 '22 14:09

fisharebest