Skip to main content

FOREIGN KEY


Pre-requisits : General understanding of integrity constraints.
Constrains are used to prevent invalid data into the table.

Integrity constrains are business rules enforced on the data in a table. The enforced rules trigger whenever a row is inserted, updated, or deleted from that table and prevent data that does not meet the set rules.

FOREIGN KEY : Establishes and enforces a relationship between two tables or to the same table itself.

The foreign key or referential integrity constraint, designates a column or combination of columns as a foreign key and establishes a relationship between a primary key or a unique key in the same table or a different table.

 In the example below   Emp_child  table's deptno   has been defined as the foreign key ; it references the deptno column of the Dept_parent table.


Implementation:

Step 1
Create parent table DEPT_PARENT as follows:

Create table DEPT_PARENT
( Deptno number(2) primary key,
  Dname varchar2(15),
  Loc varchar2(15)
);

Step 2

Insert rows manually or from existing default table like Dept as follows:
Insert into Dept_Parent ( select * from dept);
Commit;

Verify your data in the table by a select statement as follows :
Select * from dept_parent.

Step 3

Create Child table emp_child as follows :
CREATE TABLE EMP_child
       (EMPNO NUMBER(4) NOT NULL,
        ENAME VARCHAR2(10),
        JOB VARCHAR2(9),
        MGR NUMBER(4),
        HIREDATE DATE,
        SAL NUMBER(7, 2),
        COMM NUMBER(7, 2),
        DEPTNO NUMBER(2) references dept_parent(deptno)
        );
While creating the child table , the last line ( references dept_parent(deptno) ) is the syntax that binds the parent and the child table.

Step 4

Having established foreign key / referential integrity between two tables, we can now test the functionality of referential integrity.
To test the following functionality , load emp_child table with the data in default table emp.

Insert into emp_child (select * from emp );
Commit;

Functionality of referential integrity : 

1) No record in table emp_child can be inserted without the deptno colum of the emp_child table having one of the values that exist in the deptno column of dept_parent.

INSERT INTO EMP VALUES
        (1111, 'SMITH',  'CLERK',     7902,
        TO_DATE('17-DEC-1980', 'DD-MON-YYYY'),  800, NULL, 21);
     2) No record in table dept_master can be deleted when corresponding records exist in emp_child.

DELETE FROM DEPT_PARENT WHERE DEPTNO= 20;

    3) Deptno column in emp_child table cannot be updated with any other value that does not exist in the deptno column of dept_parent.

UPDATE EMP_CHILD SET DEPTNO =11 WHERE DEPTNO =10;

4)      Any record in emp_child can be deleted irrespective of its parent record in Dept_parent.
DELETE FROM EMP_CHILD WHERE DEPTNO= 20;

Step 5

Understanding the option  ON DELETE CASCADE:

Deletes the dependent rows in the child table when a row in the parent table is deleted.

To practice this concept follow the below:

Drop table emp_child purge;

Create Child table emp_child as follows :
CREATE TABLE EMP_child
       (EMPNO NUMBER(4) NOT NULL,
        ENAME VARCHAR2(10),
        JOB VARCHAR2(9),
        MGR NUMBER(4),
        HIREDATE DATE,
        SAL NUMBER(7, 2),
        COMM NUMBER(7, 2),
        DEPTNO NUMBER(2) references dept_parent(deptno) on delete cascade
        );

Insert rows from emp table as follows :

Insert into emp_child ( select * from emp);
Commit;

Delete a record from dept_parent and check if corresponding records are deleted in the emp_child table.

Delete from dept_parent where deptno =10;
Commit;

Select * from dept_parent;

Select * from emp_Child ; -- you would not find records for deptno 10.
  
Step 6

Understanding the option  ON DELETE SET NULL:

Setting null to child date column DEPTNO  when a row in the parent table is deleted.

To practice this concept follow the below:

Drop table emp_child;

Create Child table emp_child as follows :
CREATE TABLE EMP_child
       (EMPNO NUMBER(4) NOT NULL,
        ENAME VARCHAR2(10),
        JOB VARCHAR2(9),
        MGR NUMBER(4),
        HIREDATE DATE,
        SAL NUMBER(7, 2),
        COMM NUMBER(7, 2),
        DEPTNO NUMBER(2) references dept_parent(deptno) on delete set null
        );

Insert rows from emp table as follows :

Insert into emp_child ( select * from emp );
Commit;

Delete a record from dept_parent and check if corresponding  column DEPTNO  in the emp_child table is set to NULL.

Delete from dept_parent where deptno =10;
Commit;

Select * from dept_parent;

Select * from emp_Child ; -- you would find DEPTNO column set to null for employees who  work for deptno 10.


Comments

Shivam said…
easy to understand
Shubham said…
easily understandable using this blog.
Rehan Ahmed said…
Best step by step procedure for the tutorial on foreign key.
Unknown said…
This is really an awesome article. Very good explanation.
Yash said…
Very helpful content for understanding foreign key.
Shiladitya said…
concept became crystal clear after studying the blog.thumbs up.
Mahesh Jagtap said…
very well explained ,Thanks a lot.
Unknown said…
It is very helpful to understand need for a foreign key and under standing with example is very good .thank you very much sir
ajay said…
easy to understand and good explanation
VAISHNAVI said…
it was really helpful.
preeti said…
it is helpful to understand the concept.
Aditya said…
very helpful and easily understandable
Akash Sinha said…
thank a lot for this helpful session.
nupur pawar said…
very helpful and easy to underdstand....
sumanta said…
Very well explained , with examples...thank u sir
Unknown said…
Thanks for this blogspot..
A handy way of learning queries..
The concept is crystal clear On delete cascade and On delete set null such an important concepts as i am unable to delete the records using Delete key word i referred ubr blog Tq Ajay Sir Another imp Topic learned from u r Blog
Medini said…
Concept was really useful. Thanks for allowing us to refer the blog .Thank u sir for this awesome explanation.
vinay said…
Understod the concept of foriegn key easily after reading this blog. Thank you.
Anudeep said…
Concept of foreign key is clear and understandable. Thank you for the blog
Chandrika said…
It's a difficult topic to understand but it with these step by step procedures one can clearly understand what actually foreign key is
Unknown said…
Foreign keys and referencing is clearly explained with all possible cases. Helpful.
Vidya latha said…
Easy to understand the concept.thanks for the blog with clear explanation
Gayathri said…
Its a very nice collection of information regarding foreign key and enhanced our knowledge very much
Unknown said…
It is clear and easy to understand about foreign key.thank you sir for providing the blog
Unknown said…
Explanation is good and it is helpful for everyone.
Unknown said…
Very well explained with examples,it is very easy to understand...Thank you so much for this blog sir...
Unknown said…
Excellent and easy to understand
Unknown said…
Thank you . It was really helpful
Anuradha H D said…
This is very helpful sir. Thank you.
Nisha said…
Very well explained and easy to understand.
Rahul said…
Examples made understanding easy.
Arghadeep said…
Content is clear and easy to understand.
Sharanya S Rao said…
This comment has been removed by the author.
Rakesh said…
The topics covered are easy to understand and easy to learn.
Atreyee said…
Very helpful and easy to understand
Rakesh said…
The topics covered are easy to understand and easy to learn.
Rakesh said…
The topics covered are easy to understand and easy to learn
Explanation is good and it is helpful.
Rahul said…
Topics covered well. A lot of examples were given
Rakesh said…
The topics covered are easy to understand and easy to learn
Unknown said…
Explanation is good in brief with all example done. Thank you.
Anuradha H D said…
Very helpful content sir. Thnak you.
Unknown said…

Very helpful, easy to understand
step-by-step concept.
Pooja said…
The topics were very easy to understand. The content was very clear and was explained with examples.
Varun kumar said…
This comment has been removed by the author.
Puja said…
A good article and also very helpful, easy to understand.
Trisha said…
Well and brief explained
Rakesh said…
The topics covered are easy to understand and easy to learn.
Unknown said…
Very well explained
Arghadeep said…
Very well explained and the content is also very easy to understand.
Unknown said…
Easy to understand
Puja said…
A good article and also very helpful, Easy to understand, Thank You sir.
Nikhila said…
Easy to understand...it is very helpful
Unknown said…
Thank you sir, really helpful
Unknown said…
It is very easy to understand and helpful content
Unknown said…
Very easy to understand and covered all the typesin it.
Rahul said…
Easy to understand.
Sunshine Kookie said…
This comment has been removed by the author.
Nisha said…
Very well explained.
Sharanya S Rao said…
It gave clear picture about the concept and made easy to implement these concepts.
Thank you sir.
Unknown said…
Thank you sir. Good explanation on each and every topic...Its clear to know the query implementation based on real scenarios.
Puja said…
It is very useful and easy to understand.
By Puja Dey.
Sunshine Kookie said…
Very well explained,step by step written, easy to understand.
Varun kumar said…
This comment has been removed by the author.
Varun kumar said…
Very well explained with examples,it is very easy to understand...Thank you so much sir.,..for u r explanation
Easy to understand and good explanation
Unknown said…
It was clearly and well explained. It was easy 2 understand.it was really helpful
Priyanshi said…
This comment has been removed by the author.
Unknown said…
Nice and to the point concepts.
Ramya said…
The queries covers all the concepts that we have learnt and solving these queries made it easy to understand even better. Thank you !
Unknown said…
Understood well
Unknown said…
The concept is explained very clearly and this made it much more easier to understand
This comment has been removed by the author.
Well explained by Ajay sir.I really liked the content.

Popular posts from this blog

PL / SQL practice programs

  PL / SQL  practice programs 1. Write a program to print the following format WELCOME TO PL/SQL PROGRAMMING   BEGIN   DBMS_OUTPUT.PUT_LINE('WELCOME   TO   PL/SQL   PROGRAMMING'); END; /   2. Write a program to print the numbers from 1 to 100   DECLARE N NUMBER(3):=1; V VARCHAR2(1000); BEGIN WHILE N <=1000 LOOP V:=V||''||N; N:=N+1; END LOOP; DBMS_OUTPUT.PUT_LINE(V); END; / 3. write a program to print the even numbers from 1 to 100 DECLARE N NUMBER(3):=0; BEGIN WHILE N <=100 LOOP N:=N+2; DBMS_OUTPUT.PUT_LINE(N); END LOOP; END; / 4. Write a program to print the odd numbers from 1 to 100 DECLARE N NUMBER(3):=1; BEGIN WHILE N <=100 LOOP N:=N+2; DBMS_OUTPUT.PUT_LINE(N); END LOOP; END; / 5. write a program for multiplication table DECLARE A NUMBER(2):=&A; B   NUMBER(2):=1; C   NUMBER(3); BEGIN WHILE B <

RDBMS MINI PROJECT

  Capgemini class room training.   RDBMS MINI PROJECT ( SPRINT ) LIBRARY MANAGEMENT SYSTEM   Table of Contents Serial No. Topic Name Content Page No. 1.   Introduction 1.1 Setup checklist for mini project 3     1.2 Instructions 3 2.   Problem statement   2.1 Objective 4     2.2 Abstract of the project 4     2.3 Functional components of the project 4     2.4 Technology used 5 3.   Implementation in RDBMS LOT 3.1 Guidelines on the functionality to be built 6 4.   Evaluation 4.1 Evaluation 7     1.      Introduction This document outlines a mini project for the RDBMS LOT

sample tables

  --sample tables DROP TABLE EMP; DROP TABLE DEPT; DROP TABLE BONUS; DROP TABLE SALGRADE; DROP TABLE DUMMY;   CREATE TABLE EMP        (EMPNO NUMBER(4) NOT NULL,         ENAME VARCHAR2(10),         JOB VARCHAR2(9),         MGR NUMBER(4),         HIREDATE DATE,         SAL NUMBER(7, 2),         COMM NUMBER(7, 2),         DEPTNO NUMBER(2));   INSERT INTO EMP VALUES         (7369, 'SMITH',   'CLERK',      7902,         TO_DATE('17-DEC-1980', 'DD-MON-YYYY'),   800, NULL, 20); INSERT INTO EMP VALUES         (7499, 'ALLEN',   'SALESMAN',   7698,         TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600,   300, 30); INSERT INTO EMP VALUES         (7521, 'WARD',    'SALESMAN',   7698,         TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250,   500, 30); INSERT INTO EMP VALUES         (7566, 'JONES',   'MANAGER',    7839,         TO_DATE('2-APR-1981', 'DD-MON-YYYY'),   2975, NULL,