I want to know the use of foreign key in SQL Server as I had a debate with one of my colleagues.
I have the opinion, when two tables are connected via a foreign key, when the records are deleted from the parent table then the same reference record from the child table should also get deleted.
Say for example I have two tables, Table1 and Table2. Table1 has one record with id = 1 and Table2 has two records with id = 1. Table2 is a child table and connected with Table1 via a foreign key. Now when I try to delete the id = 1 record from Table1 then id = 1 (2 records) should be deleted from Table2 at the same time.
He says that’s wrong. In case of a foreign key, I have to separately delete records from both the tables.
Who is correct?
Both answers can be used and can work.
Your colleague’s version puts more responsability on your application (or your DBA) doing the deletion: the app (or DBA) will have to check for child rows first and delete them, and then delete the parent row. This works, and doesn’t give you any unexpected surprises.
If you put a
ON DELETE CASCADEoption on your foreign key constraint (which should be possible in just about any serious relational database system), then the behavior would be the way you describe it – that might make sense, from a business point of view (e.g. delete all order items for an order), but in other cases, it might totally make no sense at all (e.g. if you delete an order no. 1234, you typically don’t want to delete all the products the order items for that order will probably reference).So there are two scenarios – both make sense in certain scenarios, and not such much in others. It’s not a simple “either – or” / “right vs. wrong” question at all.