The ON DELETE CASCADE
action allows us to set up an action on a relationship that will delete related rows when the parent is deleted. For example, if we have employees and salaries, we can set up our database to delete related salaries when we delete an employee. In this article, we will learn ON DELETE CASCADE in MySQL.
The basic syntax of DELETE is as follows:
CREATE TABLE [table] (
id INT NOT NULL,
FOREIGN KEY ([foreign_id])
REFERENCES [foreign_table] ([foreign_id])
ON DELETE CASCADE
);
Here foreign_table is the name of the related table and the foreign_id is the linked column.
We will be using docker in this article, but feel free to install your database locally instead. Once you have docker installed, create a new file called docker-compose.yml
and add the following.
version: '3'
services:
db:
image: mysql:latest
container_name: db
environment:
MYSQL_ROOT_PASSWORD: root_pass
MYSQL_DATABASE: app_db
MYSQL_USER: db_user
MYSQL_PASSWORD: db_user_pass
ports:
- "6033:3306"
volumes:
- dbdata:/var/lib/mysql
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: pma
links:
- db
environment:
PMA_HOST: db
PMA_PORT: 3306
PMA_ARBITRARY: 1
restart: always
ports:
- 8081:80
volumes:
dbdata:
Next, run docker-compose up
.
Now, navigate to http://localhost:8081/
to access phpMyAdmin. Then log in with the username root
and pass root_pass
.
Click the SQL tab and you are ready to go.
Let’s start by creating a simply employee table.
CREATE TABLE employees (
emp_no INT NOT NULL PRIMARY KEY
);
Next, we create a salary table with a relationship to the employees. Then we add the ON DELETE CASCADE
to the foreign key.
CREATE TABLE salaries (
Id INT NOT NULL,
emp_no INT NOT NULL,
FOREIGN KEY (emp_no)
REFERENCES employees (emp_no)
ON DELETE CASCADE
);
Now, let’s insert some employees and salaries.
INSERT INTO employees VALUES (10001),
(10002);
INSERT INTO salaries VALUES (1, 10001),
(2, 10002);
Now, let's check the data.
SELECT * FROM employees e;
emp_no |
---|
10001 |
10002 |
SELECT * FROM salaries s;
id | emp_no |
---|---|
1 | 10001 |
2 | 10001 |
Then, we can delete an employee and notice the salary is also deleted.
DELETE FROM employees e where e.emp_no = 10001;```
SELECT * FROM employees e;
emp_no |
---|
10002 |
SELECT * FROM salaries s;
id | emp_no |
---|---|
2 | 10002 |