Skip to content

Commit 18abe68

Browse files
committed
understanding foreign key integrity constraint
1 parent c251ecf commit 18abe68

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
use temp_db;
2+
3+
show tables;
4+
5+
6+
-- here it is most important constraint because using this we can have relationship constraint
7+
-- like 1 - 1, 1 - M, M-1, M-M
8+
-- it will work when there are multiple tables
9+
-- lets say there are two tables so there must be a common column between them
10+
-- one is parent table and another is child table and in parent table that column must be primary key
11+
-- and in child table it will work as foreign key, also child table is dependent on parent table.
12+
/*
13+
RULES:
14+
1. Data inserted into the child table should have same data of the common column of parent table.
15+
2. Cannot delete the record from the parent table having the associated data in child table.
16+
if you have to delete this then you need to delete the child table entry first.
17+
You can do this using ON DELETE CASCADE;
18+
*/
19+
20+
-- parent table
21+
create table emp_parent(id int, name varchar(15), exp int, primary key(id));
22+
23+
insert into emp_parent values(1, 'SANOJ', 1);
24+
insert into emp_parent values(2, 'KUMAR', 2);
25+
insert into emp_parent values(3, 'DEEPAK', 3);
26+
27+
-- child table
28+
create table salary_child(id int, salary int, foreign key(id) references emp_parent(id));
29+
30+
insert into salary_child values(1, 10000); -- no error
31+
insert into salary_child values(9, 1000000); -- will give error because 9 is not present in parent table
32+
insert into salary_child values(2, 200000); -- no error
33+
34+
35+
-- now deleting the value in parent table
36+
delete from emp_parent where id = 1; -- will give error because it has value associated in child table
37+
38+
-- but using the ON DELETE CASCADE we can do this (also deleting one by one can also help);
39+
-- but we need to change the table strucutre and then use ON DELETE CASCADE;
40+
41+
create table salary_new(id int, salary int, foreign key(id) references emp_parent(id) on delete cascade); -- like this
42+
insert into salary_new values(1, 10000); -- no error
43+
insert into salary_new values(9, 1000000); -- will give error because 9 is not present in parent table
44+
insert into salary_new values(2, 200000); -- no error
45+
46+
delete from emp_parent where id = 1; -- here it will not work because it has dependencies on two tables now so we need to remove that first
47+
48+
-- now deleted from salary_child but not from the salary_new
49+
delete from salary_child where id = 1;
50+
51+
-- this will work
52+
delete from emp_parent where id = 1;
53+
54+
55+
select * from emp_parent;
56+
57+
select * from salary_child;
58+
59+
select * from salary_new;

0 commit comments

Comments
 (0)