SQL Day 5: Cascading Referential Integrity Constraint
LO 1: Cascading Referential Integrity Constraint
Prerequisite: Creating Table, Adding Default Constraint
Cascading Referential Integrity constraint allows to define the actions SQL Server should take when use attempts to delete or update a key to which an existing foreign key points.
For example, If you delete the row with id=1 from the tblGender table, then row with id=1 from tblEmployee table becomes an orphan record.
So, cascading referential integrity can be used to define actions SQL server should take when this happen. By Default, we get an error when performing update or delete operations.
If you remember in previous post “Creating Tables & Enforcing Primary and Foreign Key” we had created a Foreign Key relationship as the display in the following screen. Right click on this key and click on Modify.
A new window will be displayed in which you can see “Insert And Update Specification” at last and on expand this you will see the Delete Rule and Update Rule.
By Default, No Action is selected and because of this we have seen an error when performing Update and Delete operation.
In Delete and Update Rule we have four options from which we can select what operation need to perform when this happen. The four operations are:
- No Action
- Cascade
- Set Null
- Set Default
Let’s discuss in details.
No Action: This is the default behavior. No action specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and Update and Delete are rolled back.
Set Default: When an attempt is made to update or delete a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to default values.
After setting “Set Default” click on the Close button and then press Ctrl + S to save the table and click Yes on Save dialog.
Now changes are saved and let’s perform the delete operation on the tblGender table.
Delete query get executed. Now see what will happen on the tblEmployee table. For row id=1, 3 has been updated because this is the default value.
Set Null: When an attempt is made to update or delete a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to NULL.
Cascade: When an attempt is made to update or delete a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are deleted or updated.
Perform same steps as above to set Cascade.
Before running the delete query lets see what both tables contain.
Now on executing the delete query on the tblGender table for id=3 then all rows in tblEmployee which have match gets deleted.
That’s all for today. Thank You.
Comments
Post a Comment