0% found this document useful (0 votes)
11 views2 pages

MySQL 8, ON DELETE & ON UPDATE

Uploaded by

jsersan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

MySQL 8, ON DELETE & ON UPDATE

Uploaded by

jsersan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

MySQL 8.0.

22 | On Update Cascade & Delete Cascade + Set Null

1. On Update Cascade & Delete Cascade

https://www.mysqltutorial.org/mysql-on-delete-cascade/

***** 1. Parent Table *****

create table member(


id varchar(3) primary key,
name varchar(5)
);

***** 2. Child Table *****

create table car(


id varchar(3),
carNum varchar(4),
foreign key(id) references member(id)
on delete cascade
on update cascade
);

Now let’s test it if we used it right.

insert into member values ('AAA', 'Nina'), ('BBB', 'Tom'),


('CCC','Amy');

insert into car values ('AAA', '1234'), ('AAA', '4567'),


('BBB', '7777'), ('CCC','0000');

Put these tuples in each table and see what happens if I change the id ‘AAA’ into
‘DDD’ in the parent table.

mysql> update member set id='DDD' where id='AAA';


Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0mysql> select * from member;
+-----+------+
| id | name |
+-----+------+
| BBB | Tom |
| CCC | Amy |
| DDD | Nina |
+-----+------+
3 rows in set (0.00 sec)mysql> select * from car;
+------+--------+
| id | carNum |
+------+--------+
| DDD | 1234 |
| DDD | 4567 |
| BBB | 7777 |
| CCC | 0000 |
+------+--------+
4 rows in set (0.00 sec)
Without any errors, we could change the information from the parent table, and when
we changed it, this affected on the child table as well.
Now I’ll delete the information of id ‘BBB’ in the parent table.

mysql> delete from member where id='BBB';


Query OK, 1 row affected (0.01 sec)mysql> select * from member;
+-----+------+
| id | name |
+-----+------+
| CCC | Amy |
| DDD | Nina |
+-----+------+
2 rows in set (0.00 sec)mysql> select * from car;
+------+--------+
| id | carNum |
+------+--------+
| DDD | 1234 |
| DDD | 4567 |
| CCC | 0000 |
+------+--------+
3 rows in set (0.00 sec)

That was easy!

You might also like