0% found this document useful (0 votes)
16 views5 pages

Foreign Key Constraint

Uploaded by

artdebjeetsaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

Foreign Key Constraint

Uploaded by

artdebjeetsaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Foreign Key Constraint

reference one another through


common fields validitv of
and to ensure
In anRDBMS, tables
is enforced. Referential integrity is a system of rules that a
references, referential integrity
in related tables are valid, and that
DBMS uses to ensure that relationships between records
users don't delete or
accidentally related data. Referential integrity is ensured through_
change
FOREIGN KEY constraint. This is implemented as explained in the following paragraph.
Whenever two tables are related by a common column (or set of columns), then the relatec
column(s) in the parent table (or primary table) should be either declared a PRIMARY KEY o-
UNIQUE key and the related column(s) in the child table (or related table) should hav
OREIGN KEY constraint. For instance, if we have following two tables:

Items (Itemno, Description, Price, QOH) Underlined columns indicate


Orders (Orderno, Orderdate, Itemno, Qty) primary key
7ABLE CRE

571
rough
elated thro common column
tatbles
a r e

Items
and it
it nd should be declared Itemno. The column Itemno is
t h e able
t ht i a lntegritp i.e.,
e,n
both the i foreign key in child table Orders
tables should be created ary
ity to enforce
CREATE TABLE I t e
as
follows
no char(5) NOT NULL PRIMARY KEY,

CREATE TABLE O r d e r s
child table.
);
O r d e r n o
Number (6, e) OT NULL PRIMARY KEY,
Ttemno char(5) REFERENCES Items (Itemno), primary key of parent table.

foreign key parent table's name

related column Itemno in child table Orders


has been
He
Notice
that the

thaRENCES clause.
REFERENCI
To enforce a foreign
key
constraint at column
declared foreign key
through
level, the syntax to
he
tollowedi s

SINTAX
olumnna datatype (size) REFERENCES tablename
eolumnname) ] [ON DELETE CASCADE] [ON UPDATE CASCADE 1?
[(co.

he first columnname is the name of related column in child table and the columnname
Herethe REFERENCES clause is the name of related column in the parent table. The
appearing after RE)
Ppafter
ilename after EFERENCES
REF clause is the name of parent table or primary table to which the
c u r r e n t table is related.
olumn
in
related columnname in parent table, then, by default MySQL will reference
you skip the of parent table.
the primary key
CASCADE also, while defining foreign key constraint then in
Tfyou write ON DELETE
a row o r a tuple
is deleted in parent table, all its related tuples or rows in the child table
deleted.
will automatically be
constraint then in
ON UPDATE CASCADE also, while defining foreign key
Ifyou write
related tuples or rows in the child table
case a row o r a is updated in parent table, all its
tuple
will automatically be updated.
as
FOREIGN KEY table constraint,
constraint c a n also be applied through
Ihe foreign key
shown below: NOT NULL PRIMARY KEY,
OrderID SMALLINT
CREATE TABLE Orders ( NOT NULL,
ModelID SMALLINT
ModelDescrip VARCHAR (40),
SMALLINT NOT NULL,
SupplierID REFERENCES
Models (ModelID)
FOREIGN KEY
(ModelID)
CASCADE,
CASCADE ON UPDATE (SupplierID)
DELETE Suppliers
HodeliID and SupplieriD are ON
KEY (SupplierID)
REFERENCES

Deing defined as FOREIGN CASCADE )


foreign keys DELETE
CASCADE ON UPDATE ACTION will
ON operation; NO
RESTRICT will
reject the will set NULL in
can also use of CASCADE. on it; SETNULL
RESTRICT |SET NULL .NO ACTION in place there is a foreign key
dependent

talow deletion orsupdation


e deletionor of ajprimary key as long
as

foreign key column.


L r a
itresults nto the rejection ot INSERT (#tatemnt thel t i e i l nw data
(statement Ned t nnndity eninting data) if atoH linH Value dvn d " UI)
DA
n the prinmary hable ( ig 1 ) ently
It ON DEETE CAS ADE optiom han bwen nel tlen umn eleletinug a tuuplr i s
tatble all its elated reonds i the hild table get deetel In te abeme abenee of this te parent
ejets the deletiom operatinm it eesponndiug e o d : in the ahind lute exint
\ae,
he nuunt eterenee lRIMARY
toeign key olmn in the hill table a
KEY or UNOU
vlumn in the purent table
oth the n'latendovlnns (in pant talbk and indik| table) rlunikl uave theue
ame data
dats typo
May reterenee to the same table in whih it in Ding, lelined 1t, il may referonces
table
nane as in the C'REATE TABII command

Let me check Ecode nama rada


why this error 1101 Brian
101 M E3 12000
Occurted tiran M 12000
Hvn! The raason
behind it is the
1102 Maithtl MI 1t0000 DELETE FROM
vioNatiovn of 103 Kushagra M M 24000
REFERENCES 1104
0onstraint on Vansh M M3 24000 Errorl While
Ecode colunwn. deloting
REFERENCES
I am
foreign kay in
my tabla
Peode Decscrp Ecoda Due On
REFERENCES P7 01
F constrant on
Ecode column PZ-02
Sales Mgt
Malthili
1103
1104
12/11/2001
02/01/2002
PZ-03 Kushagra 1102 15/03/2002
PZ-04 Vansh 1101 18/06/2002

Fiqune
13.FOREIGN KEY/REFERENCE Constraint.
Important Foreign Key and Storgge Engne
MySQL is capable of creating databases in many
default storage engine different storage
is ISAM but
ironically it engines that offer different features. The
does not support
foreign key constraint are being foreign keys. So, if
database tables to InnoDB ignored or not implemented, you need
you find that your
storage engine.
to
change the storage
engine of your
To do so you simply need to write following
command for your connecting tables
ALTER TABLE
«tablename>
ALTER TABLE tablel ENGINEENGINE innodb;
innodb =

Once done, you can create and implememt foreign keys for your
tables.
13.3.1B Applying Table Constraints
When a constraint is to be
applied on a group of columns of
constraint. The table constraints ble
in the end of the table, it is called
combination of icode and descp ofappear
table items to
table definition. For
instance, it you
be
unique, you may write it as folloWS
AMANDS
REATE
ABLE
It ems
1Cod
har (5)
NOT NULL, 573
har (20)
des NOT NULL,
ROL integer
QOH integer,
CHECK (ROL <QOH),
UNIQUE (icode, descp) ) these are a
table
constraints
h e
aboveS t a t e m e

ensures that the


want to define combination of ioxde and
inilarly,i tyou
primary key that contains desc in each row must be
raint. For
KEY table constraint.
nARY
the combination of instance, if you more than one o
column, you
unique
can use
want
columns firstname and to declare a
RZMA

mmtersa s
CREATE ABLE members tname, it can beprimary
lastnan key for the table
done
firstname char
as follows:
(15) NOT NULL,
lastname char (15) NOT
city char (20) NULL
PRIMARY KEY (tirstname, lastname)) this is a table constraint
.areign key constraint for a
cod. For example, it a groupgroup of
o define

columns, FOREIGN KEY table


say orderno and items, is to beconstraints
shouldbe of columns
oreign key, it.should be done as follows:
declared
CREATE TABLE Orders

( orderno Number (6, 0) NOT NULL,

Itemno char(5),

FOREIGN KEY (Orderno, Itemno) REFERENCES OrdMaster (OrderNO, ItemNO)

Names to Constraints
131C Assigning
Rv default, MysQL assigns a unique name to each constraint defined by you. MySQL names

constraints as
SYS_Cn
where n is an integer that unique. For instance, SYS_CO03217,
makes the constraint name

constraint names generated by MySQL. However, you, yourself,


can
SYS CO01592 etc. are
be done as per following syntax :
name aconstraint created you. This can by
CONSTRAINT <name-of-constraint> <definition-of-constraint>

SYNTAX
TABLE statements:
two CREATE
the following
forexample, consider
CREATE TABLE Items
CONSTRAINT p_Itemkey PRIMARY KEY,
Itemno char(5)

;
CREATE TABLE Orders
Orderno Itemno)
(Orderno,
FOREIGN KEY
fkey Orders
ONSTRAINT Group Itemt)
(Order#,
REFERENCESOrdMaster
ON -
574
st"e
icture

tRAMPLE 1 Create table Emplovee with the folloung


User_ID
First_Name
Last_Name
Salary
Name of Column ID Varchar(30) Varchar(10) Number(9,2)
Varchar(30)Varchar(10)

Type Number(4)

:
in created table
Ensure the follouing specification User_lD should
be unique
ID should be declared as Primary Key
First_Name & Last_Name must not remain
Salary must be greater than 5000. blant
Solution. CREATE TABLE Employee
PRIMARY KEY,
ID Number (4) NOT NULL
NULL,
First_Name Varchar(30) NOT
Last_Name Varchar (30) NOT NULL,
User_ID Varchar (10) UNIQUE,
CHECK (Salary> 5000) )
Salary Number (9,2)
affected
MySQL responds as: Query OK, 0 rows

MPLE 13.2 Create anothertable Job with following structure:

Name of column Type


Job_id Number(4)
Job_des Varchar(30)
Alloc_on Date
Due_on Date
Emp_id Number(4)
Ensure the following specifications in the table:
Job_idis the primary key
Job_des, Alloc_on, Due_on cannot be left
Emp_idis foreign key here that is related to ID column of blank.
earlier created table Employee.
lution. CREATE TABLE Job
Job_id Number (4) NOT NULL PRIMARY KEY,
Job_Des Varchar (30) NOT NULL,
Alloc_on Date NOT NULL, NOTE
Due_on Date NOT NULL, It you want to view the CREATE
Emp_id Number(4) REFERENCES TABLE statement of an existng
QL responds as
Query OK, 0
Employee (ID) ) ; table, you may
S H O W

rows affected mayename


CREATE TABLE ctablename
iewing a Table Structure

You might also like