Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with circular reference when entering data in SQL

Tags:

sql

What kind of sql tricks you use to enter data into two tables with a circular reference in between.

Employees
    EmployeeID <PK>
    DepartmentID <FK> NOT NULL

Departments
    DepartmentID <PK>
    EmployeeID <FK> NOT NULL

The employee belongs to a department, a department has to have a manager (department head).

Do I have to disable constraints for the insert to happen?

like image 314
tstojecki Avatar asked Jun 05 '09 12:06

tstojecki


People also ask

What is circular reference in SQL?

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.

Are circular references OK?

Circular Reference means that your formula is trying to calculate the origin cell. Typically, this is considered an error. However, there are times where this error can actually be useful and you might to want to create a circular reference on purpose.

Should circular references avoid?

If there are circular references ("loops") in a data structure, the tables are associated in such a way that there is more than one path of associations between two fields. This type of data structure should be avoided as much as possible, since it might lead to ambiguities in the interpretation of data.


1 Answers

I assume your Departments.EmployeeID is a department head. What I'd do is make that column nullable; then you can create the department first, then the employee.

like image 85
chaos Avatar answered Sep 28 '22 06:09

chaos