What happens if I will delete a row from MySQL parent table?


While deleting the row from the parent table, if the data of that row is used in the child table then MySQL will throw an error because of the failure of FOREIGN KEY constraint. It can be understood with the example of two tables named ‘customer’ and ‘orders’. Here, ‘customer’ is the parent table and ‘orders’ is the child table. We cannot delete a row, that is used in child table ‘orders’, from the ‘customer’ table. It can be demonstrated by deleting the values from the parent table as follows −

mysql> Select * from Customer;
+----+--------+
| id | name   |
+----+--------+
| 1  | Gaurav |
| 2  | Raman  |
| 3  | Harshit|
| 4  | Aarav  |
+----+--------+
4 rows in set (0.00 sec)

mysql> Select * from orders;
+----------+----------+------+
| order_id | product  | id   |
+----------+----------+------+
| 100      | Notebook | 1    |
| 110      | Pen      | 1    |
| 120      | Book     | 2    |
| 130      | Charts   | 2    |
+----------+----------+------+
4 rows in set (0.00 sec)

Now, suppose if we will try to delete the row having id = 1 or id =2 (because of both the rows used in child table) from parent table ‘customer’, then MySQL throws an error as follows due to the failure of foreign key constraint.

mysql> Delete from customer where id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`))

mysql> Delete from customer where id = 2;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`)REFERENCES `customer` (`id`))

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 28-Jan-2020

918 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements