FOREIGN KEY Constraint/ referential integrity constraint
Definition
Foreign key is an Input/output data constraint which is also known as referential integrity
constraint. Foreign key represents a link or say a relationship between columns of tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.
Reference keyword is used to create foreign key constraint
Seema Kumari ,SCA , Asst. Prof
---------create author table----------------------------------------------------------------
create table author
(
author_id int primary key,
author_name varchar(23)
Seema Kumari ,SCA , Asst. Prof
);
---------------------create books table---------------------
create table books
(
book_id int Primary key,
author_id int ,
book_name varchar(21)
constraint fkk foreign key(author_id) references
author(author_id)
);
-----------drop constaint--------------------
alter table books drop constraint fkk;
------------------- 2ND WAY TO CREATE OR add foreign key----------------------------------------
alter table books add constraint fkk foreign
key(author_id) references author(author_id);
-------------------------insertion-------------------------------
----------------------deletion---------------------------------------
--------------------------------updation--------------------------
ON DELETE SET NULL
create table author
(
Seema Kumari ,SCA , Asst. Prof
author_id int primary key,
author_name varchar(23)
);
create table books
(
book_id int Primary key,
author_id int ,
book_name varchar(21)
constraint fkk foreign key(author_id) references
author(author_id)ON
DELETE SET NULL
);
ON DELETE CASCADE
create table author
(
author_id int primary key,
author_name varchar(23)
);
create table books
(
book_id int Primary key,
author_id int ,
book_name varchar(21)
constraint fkk foreign key(author_id) references
author(author_id)ON
DELETE CASCADE
);
Seema Kumari ,SCA , Asst. Prof
Seema Kumari ,SCA , Asst. Prof