Professional Documents
Culture Documents
Dr Mohamed A Sheriff
Declarative Constraints
2
Declarative Constraints
Definition:
A mechanism provided in SQL to:
3
Declarative Constraints
Five types of declarative constraints
PRIMARY KEY
NOT NULL
UNIQUE
CHECK
FOREIGN KEY
4
The PRIMARY KEY constraint
Used to maintain the entity integrity rule
– Column value must be unique in the table
– Column value cannot be NULL
Example
Create table STUDENT (
SID Number (5) constraint PK_STD Primary Key,
SNAME Varchar2 (30)
DNAME Varchar2 (30)
SLEVEL Number (1));
A column constraint
5
The PRIMARY KEY constraint
Table Constraint
Create table STUDENT (
SID Number (5),
SNAME Varchar2 (30),
DNAME Varchar2 (30),
SLEVEL Number (1),
Constraint PK_STD Primary Key (SID));
Example
Create table STUDENT (
SID Number (5),
SNAME Varchar2 (30),
DNAME Varchar2 (30) NOT NULL,
SLEVEL Number (1) NOT NULL,
SEMAIL Varchar2 (40) Constraint STD_SEMAIL UNIQUE,
Constraint PK_STD Primary Key (SID)); 8
The Check Constraint
Defines a list of values allowed in a column
Example
Create table STUDENT (
SID Number (5),
SNAME Varchar2 (30),
DNAME Varchar2 (30) NOT NULL,
SLEVEL Number (1) NOT NULL
Constraint CK-STD_LEVEL
Check ((SLEVEL >=0)
And (SLEVEL<=3)),
Constraint PK-STD Primary Key (SID));
9
The Check Constraint
Constraint CK_STD_VALIDITY
Check (((SLEVEL>=0
And SLEVEL<=3))
And
(DNAME IN (‘Computing Science’, ‘Information Technology’));
11
The FOREIGN KEY Constraint
Enforces Referential Integrity
Example
Create table STD_RECORD (
SID Number (5),
Code Varchar2 (6),
Mark number (3)
Constraint PK_STD_RECORD Primary Key (SID, Code),
Parent table:
DBMS takes appropriate actions on UPDATE or DELETE of
key values that are referenced by child table
Example
Create table STD_RECORD (
SID Number (5),
Code Varchar2 (6),
Mark number (3)
Constraint PK_STD_RECORD Primary Key (SID, Code),
Foreign Key (SID) references STUDENT
On Delete Cascade,
Foreign Key (Code) References MODULE); 14
Example
Create table Patient (
PID Number (5),
Sname Varchar2 (15),
Fname Varchar2(15),
GPID Number (3)
Constraint PK_Patient Primary Key (PID),
Foreign Key (GPID) references GP
On Delete SET NULL, 15