When are two tables connected with MySQL FOREIGN KEY then how can we say that the integrity of data is maintained in child table?

MySQLMySQLi Database

Actually, foreign keys enforce referential integrity that helps us to maintain the consistency and integrity of the data automatically. 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 create an order for a non-existent customer. It can be demonstrated by inserting the values in both the tables 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 insert the value in the ‘orders’ table for a non-existing customer (id 10 is not existing in ‘customer’ table) then MySQL throws an error as follows due to the failure of foreign key constraint.

mysql> insert into orders values(400, 'Notebook',10);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`query`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`id`) REFERENCES `customer` (`id`))
raja
Published on 19-Feb-2018 10:01:28
Advertisements