- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When are two tables connected with MySQL FOREIGN KEY then how can we say that the integrity of data is maintained in child table?
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`))
Advertisements
To Continue Learning Please Login
Login with Google