I am going back to the basics here. I realized that in my quest for learning advanced topics, I tend to get a bit rusty with the basics. Hence I am creating a new a new basics tag for my posts and will be creating very basic posts with this tag.
Foreign key (FK) constraints allow you to create relationships between two tables. One of the tables will be treated as a parent table and the other table will be treated as the child. The FK constraint will connect one column from the parent with one column of the child.
-- Creating the parent table and adding constraints. CREATE table parent ( id int identity, value int ) alter table parent alter column id int not null alter table parent add constraint pk_parent_id primary key (id) -- Creating the child table and adding constraints. CREATE table child ( id int identity, parent_id int, value int ) alter table child alter column id int not null alter table child add constraint pk_child_id primary key (id) alter table child add constraint fk_child_parent_parent_id foreign key(parent_id) references parent(id)
You cannot delete a row from the parent table, if there is a related row in the child table. You can delete rows from the child table without issues.
-- Inserting a row into the parent table and a related row into the child table. insert into parent VALUES (20) INSERT INTO child(parent_id,value) VALUES (1,10) -- Trying to delete the previously inserted row from the parent will give an error. delete FROM parent where id=1 Msg 547, Level 16, State 0, Line 1 The DELETE statement conflicted with the REFERENCE constraint "fk_child_parent_parent_id". The conflict occurred in database "dba", table "dbo.child", column 'parent_id'. The statement has been terminated.
You cannot insert a row into the child table’s column (that is restricted by the foreign key) if that value does not exist in the parent table. You can insert rows into the parent table without issues.
-- If there is no value in parent.id = 111, the row below will error out. INSERT INTO child(parent_id,value) VALUES (111,10)
Msg 547, Level 16, State 0, Line 1The INSERT statement conflicted with the FOREIGN KEY constraint “fk_child_parent_parent_id”. The conflict occurred in database “dba”, table “dbo.parent”, column ‘id’.The statement has been terminated.
To delete rows from the parent table, you can use a cascade on delete. Another manual method is to delete all the referenced child rows and then to delete the parent row. The similar restrictions apply for updating rows to the related tables.