DELETE CASCADE And UPDATE CASCADE In SQL Server Foreign ...
Maybe your like
In this article, we will review on DELETE CASCADE AND UPDATE CASCADE rules in SQL Server foreign key with different examples.
DELETE CASCADE: When we create a foreign key using this option, it deletes the referencing rows in the child table when the referenced row is deleted in the parent table which has a primary key.
UPDATE CASCADE: When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child table when the referenced row is updated in the parent table which has a primary key.
We will be discussing the following topics in this article:
- Creating DELETE and UPDATE CASCADE rule in a foreign key using SQL Server management studio
- Creating DELETE CASCADE and UPDATE CASCADE rule in a foreign key using T-SQL script
- Triggers on a table with DELETE or UPDATE cascading foreign key
Let us see how to create a foreign key with DELETE and UPDATE CASCADE rules along with few examples.
Creating a foreign key with DELETE and UPDATE CASCADE rules
Using the SQL Server Management Studio GUI:
Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key.
Edit table and columns specification by clicking … as shown in the below image.
Select the parent table and the primary key column in the parent table. select the foreign key column in the child table. Click on OK. Please refer to the below sample image.
In the INSERT and UPDATE specifications, select Cascade for the delete rule.
Click on Close and save the table in the designer. Click Yes in the warning message window.
Once you click on Yes, a foreign key with delete rule is created. Similarly, we can create a foreign key with UPDATE CASCADE rule by selecting CASCADE as an action for the update rule in INSERT and UPDATE specifications.
Using T-SQL:
Please refer to the below T-SQL script which creates a parent, child table and a foreign key on the child table with DELETE CASCADE rule.
| 1234567891011121314151617181920212223 | CREATETABLECountries (CountryIDINTPRIMARYKEY,CountryNameVARCHAR(50),CountryCodeVARCHAR(3)) CREATETABLEStates (StateIDINTPRIMARYKEY,StateNameVARCHAR(50),StateCodeVARCHAR(3),CountryIDINT) ALTERTABLE[dbo].[States]WITHCHECKADDCONSTRAINT[FK_States_Countries]FOREIGNKEY([CountryID])REFERENCES[dbo].[Countries]([CountryID])ONDELETECASCADEGO ALTERTABLE[dbo].[States]CHECKCONSTRAINT[FK_States_Countries]GO |
Insert some sample data using below T-SQL script.
| 123456 | INSERTINTOCountriesVALUES(1,'United States','USA') INSERTINTOCountriesVALUES(2,'United Kingdom','UK') INSERTINTOStatesVALUES(1,'Texas','TX',1)INSERTINTOStatesVALUES(2,'Arizona','AZ',1) |
Now I deleted a row in the parent table with CountryID =1 which also deletes the rows in the child table which has CountryID =1.
Please refer to the below T-SQL script to create a foreign key with UPDATE CASCADE rule.
| 123456789101112131415161718192021222324252627282930313233 | CREATETABLECountries (CountryIDINTPRIMARYKEY,CountryNameVARCHAR(50),CountryCodeVARCHAR(3)) CREATETABLEStates (StateIDINTPRIMARYKEY,StateNameVARCHAR(50),StateCodeVARCHAR(3),CountryIDINT) GO INSERTINTOCountriesVALUES(1,'United States','USA') INSERTINTOCountriesVALUES(2,'United Kingdom','UK') INSERTINTOStatesVALUES(1,'Texas','TX',1)INSERTINTOStatesVALUES(2,'Arizona','AZ',1) GO ALTERTABLE[dbo].[States]WITHCHECKADDCONSTRAINT[FK_States_Countries]FOREIGNKEY([CountryID])REFERENCES[dbo].[Countries]([CountryID])ONUPDATECASCADEGO ALTERTABLE[dbo].[States]CHECKCONSTRAINT[FK_States_Countries]GO |
Now update CountryID in the Countries for a row which also updates the referencing rows in the child table States.
| 1 | UPDATECountriesSETCountryID=3whereCountryID=1 |
Following is the T-SQL script which creates a foreign key with cascade as UPDATE and DELETE rules.
| 12345678 | ALTERTABLE[dbo].[States]WITHCHECKADDCONSTRAINT[FK_States_Countries]FOREIGNKEY([CountryID])REFERENCES[dbo].[Countries]([CountryID])ONUPDATECASCADEONDELETECASCADEGO ALTERTABLE[dbo].[States]CHECKCONSTRAINT[FK_States_Countries]GO |
To know the update and delete actions in the foreign key, query sys.foreign_keys view. Replace the constraint name in the script.
| 1 | SELECTname,delete_referential_action,delete_referential_action_desc,update_referential_action,update_referential_action_descFROMsys.foreign_keyswherename='FK_States_Countries' |
The below image shows that a DELETE CASCADE action and no UPDATE action is defined on the foreign key.
Let’s move forward and check the behavior of delete and update rules the foreign keys on a child table which acts as parent table to another child table. The below example demonstrates this scenario.
In this case, “Countries” is the parent table of the “States” table and the “States” table is the parent table of Cities table.
We will create a foreign key now with cascade as delete rule on States table which references to CountryID in parent table Countries.
| 12345678910111213141516171819202122232425262728293031323334353637383940 | CREATETABLECountries (CountryIDINTPRIMARYKEY,CountryNameVARCHAR(50),CountryCodeVARCHAR(3)) CREATETABLEStates (StateIDINTPRIMARYKEY,StateNameVARCHAR(50),StateCodeVARCHAR(3),CountryIDINT) GO CREATETABLECities(CityIDINT,CityNamevarchar(50),StateIDINT)GO INSERTINTOCountriesVALUES(1,'United States','USA') INSERTINTOCountriesVALUES(2,'United Kingdom','UK') INSERTINTOStatesVALUES(1,'Texas','TX',1)INSERTINTOStatesVALUES(2,'Arizona','AZ',1) INSERTINTOCitiesVALUES(1,'Texas City',1)INSERTINTOCitiesvalues(1,'Phoenix',2) GO ALTERTABLE[dbo].[States]WITHCHECKADDCONSTRAINT[FK_States_Countries]FOREIGNKEY([CountryID])REFERENCES[dbo].[Countries]([CountryID])ONDELETECASCADEGO |
Now on the Cities table, create a foreign key without a DELETE CASCADE rule.
| 123 | ALTERTABLE[dbo].[Cities]WITHCHECKADDCONSTRAINT[FK_Cities_States]FOREIGNKEY([StateID])REFERENCES[dbo].[States]([StateID])GO |
If we try to delete a record with CountryID =1, it will throw an error as delete on parent table “Countries” tries to delete the referencing rows in the child table States. But on Cities table, we have a foreign key constraint with no action for delete and the referenced value still exists in the table.
| 1 | DELETEFROMCountrieswhereCountryID=1 |
The delete fails at the second foreign key.
When we create the second foreign key with cascade as delete rule then the above delete command runs successfully by deleting records in the child table “States” which in turn deletes records in the second child table “Cities”.
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 | CREATETABLECountries (CountryIDINTPRIMARYKEY,CountryNameVARCHAR(50),CountryCodeVARCHAR(3)) CREATETABLEStates (StateIDINTPRIMARYKEY,StateNameVARCHAR(50),StateCodeVARCHAR(3),CountryIDINT) GO CREATETABLECities(CityIDINT,CityNamevarchar(50),StateIDINT)GO INSERTINTOCountriesVALUES(1,'United States','USA') INSERTINTOCountriesVALUES(2,'United Kingdom','UK') INSERTINTOStatesVALUES(1,'Texas','TX',1)INSERTINTOStatesVALUES(2,'Arizona','AZ',1) INSERTINTOCitiesVALUES(1,'Texas City',1)INSERTINTOCitiesvalues(1,'Phoenix',2) GO ALTERTABLE[dbo].[States]WITHCHECKADDCONSTRAINT[FK_States_Countries]FOREIGNKEY([CountryID])REFERENCES[dbo].[Countries]([CountryID])ONDELETECASCADEGO ALTERTABLE[dbo].[Cities]WITHCHECKADDCONSTRAINT[FK_Cities_States]FOREIGNKEY([StateID])REFERENCES[dbo].[States]([StateID])ONDELETECASCADEGO DELETEFROMCountrieswhereCountryID=1 |
Triggers on a table with delete cascade or update cascade foreign key
An instead of an update trigger cannot be created on the table if a foreign key on with UPDATE CASCADE already exists on the table. It throws an error “Cannot create INSTEAD OF DELETE or INSTEAD OF UPDATE TRIGGER ‘trigger name’ on table ‘table name’. This is because the table has a FOREIGN KEY with cascading DELETE or UPDATE.”
Similarly, we cannot create INSTEAD OF DELETE trigger on the table when a foreign key CASCADE DELETE rule already exists on the table.
Conclusion
In this article, we explored a few examples on DELETE CASCADE and UPDATE CASCADE rules in SQL Server foreign key. In case you have any questions, please feel free to ask in the comment section below.
Please refer to this article, SQL Server foreign key to dig in more details on delete and update rules in SQL Server foreign key.
- Author
- Recent Posts
- Geo Replication on Transparent Data Encryption (TDE) enabled Azure SQL databases - October 24, 2019
- Overview of the Collate SQL command - October 22, 2019
- Recover a lost SA password - September 20, 2019
Related posts:
- SQL Server Replication with a table with more than 246 columns
- ELIMINAR EN CASCADA y ACTUALIZAR CASCADA en la clave externa de SQL Server
- Commonly used SQL Server Constraints: FOREIGN KEY, CHECK and DEFAULT
- The benefits, costs, and documentation of database constraints
- SQL Foreign key
Tag » Add Constraint On Delete Cascade Mysql
-
How To Add 'ON DELETE CASCADE' In ALTER TABLE Statement
-
MySQL 8.0 Reference Manual :: 13.1.20.5 FOREIGN KEY Constraints
-
Alter Table To Remove Foreign Key Or Add DELETE CASCADE (MySQL)
-
MySQL ON DELETE CASCADE - Javatpoint
-
MySQL ON DELETE CASCADE: Deleting Data From Related Tables ...
-
MySQL - ON DELETE CASCADE Constraint - GeeksforGeeks
-
Mysql Alter Table Add Constraint Foreign Key On Delete Cascade Code ...
-
SQL Server: Foreign Keys With Cascade Delete - TechOnTheNet
-
MySQL DELETE CASCADE - Linux Hint
-
[Résolu] Sql | Comment Ajouter 'ON DELETE CASCADE' Dans
-
13.1.17.5 FOREIGN KEY Constraints - Oracle Help Center
-
Add ON DELETE CASCADE To Foreign Key Constraint
-
Using The ON DELETE CASCADE Option - IBM
-
MySQL ON DELETE CASCADE - StackHowTo