Examples of SQL Cascade
Let’s create the database in SQL server management studio and then create a a parent table (which contains the primary key) and child table (which contains the foreign key) in the SQL server and insert some data into it and then we will perform different cascade operations into it.
Create Database
CREATE DATABASE Cascading;
USE Cascading;
Create a Parent Table
CREATE TABLE Authors (
AuthorID INT PRIMARY KEY,
AuthorName VARCHAR(200)
);
Create a Child Table
CREATE TABLE Books (
BookID INT PRIMARY KEY,
Title VARCHAR(255),
AuthorID INT,
FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID) ON DELETE CASCADE
);
Output:
You can see that the database and table were created successfully.
Insert data into Authors table
INSERT INTO Authors (AuthorID, AuthorName) VALUES (1, 'John Doe');
INSERT INTO Authors (AuthorID, AuthorName) VALUES (2, 'Minal Pandey');
INSERT INTO Authors (AuthorID, AuthorName) VALUES (3, 'Mahi Pandey');
Insert data into the Books table, automatically linked to the Authors table
INSERT INTO Books (BookID, Title, AuthorID) VALUES (101, 'Introduction to SQL', 1);
INSERT INTO Books (BookID, Title, AuthorID) VALUES (102, 'Database Fundamentals', 2);
INSERT INTO Books (BookID, Title, AuthorID) VALUES (103, 'Advanced SQL', 2);
INSERT INTO Books (BookID, Title, AuthorID) VALUES (104, 'Web Development', 3);
Now check whether the data is inserted or not using the below query.
SELECT * FROM Authors;
SELECT * FROM Books;
Output:
Cascade in SQL
Structured Query Language (SQL) is a powerful tool for managing and manipulating relational databases. Maintaining data integrity is essential to database administration, particularly when working with table relationships. In this article, we can go through the idea of SQL CASCADE, a function that performs a considerable function in retaining referential integrity inside a database. The cascading referential integrity constraints in SQL servers are the foreign key constraints that tell SQL servers to perform certain actions whenever a user attempts to delete or update a primary key to which an existing foreign key points.
Contact Us