SlideShare a Scribd company logo
Copyright © 2009, Oracle. All rights reserved.
Constraints
Copyright © 2009, Oracle. All rights reserved.
9 - 2
 While creating tables in a relational database, you must ensure that
no one should enter invalid data in it. Therefore, you need to apply
certain rules and constraints for columns that specify the kind of
data to be stored.
 If the checks are not applied while defining and creating tables, the
data stored in the tables can become redundant.
 Therefore, it is important to ensure that the data stored in tables is
complete and consistent. The concept of maintaining consistency
and completeness of data is called Data Integrity.
Implementing Data Integrity
Copyright © 2009, Oracle. All rights reserved.
9 - 3
 Data integrity:
 Is enforced to ensure that the data in a database is accurate,
consistent, and reliable.
 Is broadly classified into the following categories:
 Entity integrity
 Domain integrity
 Referential integrity
Implementing Data Integrity (Contd.)
Copyright © 2009, Oracle. All rights reserved.
9 - 4
Implementing Data Integrity (Contd.)
Entity Integrity
 Ensures that each row can be uniquely identified by an attribute
called the primary key. The primary key column contains unique
value in all the rows. In addition, this column cannot be NULL.
Domain Integrity
 Ensures that only a valid range of values is stored in a column. It
can be enforced by restricting the type of data, the range of values,
and the format of the data.
Referential Integrity
 Ensures that the values of the foreign key match the value of the
corresponding primary key.
Copyright © 2009, Oracle. All rights reserved.
9 - 5
Implementing Data Integrity (Contd.)
 Constraints:
• Enforce rules that must be followed to maintain consistency
and correctness of the data.
• Constraints prevent the deletion of a table if there are
dependencies.
• The following constraint types are valid:
– NOT NULL
– UNIQUE
– PRIMARY KEY
– FOREIGN KEY
– CHECK
Types of Constraints
Copyright © 2009, Oracle. All rights reserved.
9 - 6
Guidelines
• You can name a constraint, or the Oracle server generates a name with
the SYS_Cn format.
• Create a constraint at either of the following times:
– At the time of creation of table
– After the table has been created
• Check the existing data if added after the creation of the table
• Define a constraint at the column or table level.
• View a constraint in the data dictionary.
• Can be created by using either of the following statements:
CREATE TABLE statement
ALTER TABLE statement
Copyright © 2009, Oracle. All rights reserved.
9 - 7
• Syntax:
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
column [CONSTRAINT constraint_name] constraint_type,
Defining Constraints
• Column-level constraint:
• Table-level constraint:
Note
NOT NULL constraints must be defined at the column level.
Copyright © 2009, Oracle. All rights reserved.
9 - 8
CREATE TABLE Student(
Sno Number(5),
Sname Varchar2(12),
. . .
Fees Number(8,2),
CONSTRAINT sno_pk PRIMARY KEY(Sno)
);
CREATE TABLE Student(
Sno Number(5) CONSTRAINT sno_pk PRIMARY KEY,
Sname Varchar2(12),
Course Varchar2(10),
Fees Number(8,2)
);
1
2
Defining Constraints
• Column-level constraint:
• Table-level constraint:
Copyright © 2009, Oracle. All rights reserved.
9 - 9
• Ensures that null values are not permitted for the column:
NOT NULL constraint
(No row can contain
a null value for
this column.)
Absence of NOT NULL
constraint
(Any row can contain
a null value for this
column.)
NOT NULL
constraint
…
NOT NULL Constraint
Copyright © 2009, Oracle. All rights reserved.
9 - 10
NOT NULL Constraint
Columns Data Type Checks
EmployeeID Number(5) NOT NULL
LeaveStartDate Date NOT NULL
LeaveEndDate Date NOT NULL
LeaveReason varchar(100)
LeaveType Char(2) NOT NULL
• Consider the following EmployeeLeave table.
CREATE TABLE EmployeeLeave(
EmployeeID Number(5) NOT NULL,
LeaveStartDate Date NOT NULL.
LeaveEndDate Date NOT NULL,
LeaveReason Varchar2(15),
LeaveType Char(2) NOT NULL
);
Copyright © 2009, Oracle. All rights reserved.
9 - 11
UNIQUE Constraint
• Ensures that every value in a column or set of columns (key) be
unique—that is, no two rows of a table can have duplicate values in a
specified column or set of columns.
• The column (or set of columns) included in the definition of the
UNIQUE key constraint is called the unique key.
• If the UNIQUE constraint comprises more than one column, that group
of columns is called a composite unique key.
• UNIQUE constraints enable the input of nulls unless you also define
NOT NULL constraints for the same columns.
• The Oracle server enforces the UNIQUE constraint by implicitly
creating a unique index on the unique key column or columns.
Copyright © 2009, Oracle. All rights reserved.
9 - 12
EMPLOYEES
UNIQUE constraint
INSERT INTO
Not allowed:
already exists
Allowed
…
UNIQUE Constraint
Copyright © 2009, Oracle. All rights reserved.
9 - 13
Defining UNIQUE Constraint
CREATE TABLE EmpInf(
EmpCode Number(5),
EmpName Varchar2(15) NOT NULL,
Email Varchar2(25) CONSTRAINT email_unq UNIQUE,
Salary Number(8,2)
);
• Column-level constraint:
• Table-level constraint:
CREATE TABLE EmpInf(
EmpCode Number(5),
. . .
Salary Number(8,2),
CONSTRAINT email_unq UNIQUE(Email)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 14
Defining UNIQUE Constraint
CREATE TABLE EmpInf(
EmpCode Number(5),
EmpName Varchar2(15) NOT NULL,
Email Varchar2(25)
CONSTRAINT email_nn NOT NULL
CONSTRAINT email_unq UNIQUE,
Salary Number(8,2)
);
• More than One Constraint
Copyright © 2009, Oracle. All rights reserved.
9 - 15
PRIMARY KEY Constraint
• A PRIMARY KEY constraint creates a primary key for the table. Only
one primary key can be created for each table.
• The PRIMARY KEY constraint is a column or set of columns that
uniquely identifies each row in a table.
• This constraint enforces uniqueness of the column or column
combination and ensures that no column that is part of the primary key
can contain a null value.
• It is similar to the Unique key constraint except that it does not allow
NULLrow.
Copyright © 2009, Oracle. All rights reserved.
9 - 16
DEPARTMENTS
PRIMARY KEY
INSERT INTO
Not allowed
(null value)
Not allowed
(50 already exists)
…
PRIMARY KEY Constraint
Copyright © 2009, Oracle. All rights reserved.
9 - 17
Defining PRIMARY KEY Constraint
CREATE TABLE Department(
DeptNo Number(5) CONSTRAINT dept_pk PRIMARY KEY,
DeptName Varchar2(15) NOT NULL,
Location Varchar2(25) NOT NULL,
);
• Column-level constraint:
• Table-level constraint:
CREATE TABLE Department(
DeptNo Number(5),
DeptName Varchar2(15) NOT NULL,
Location Varchar2(25) NOT NULL,
CONSTRAINT dept_pk PRIMARY KEY(DeptNo)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 18
Defining PRIMARY KEY Constraint
• Composite Primary Key
Create Table EmployeeLeave(
EmployeeID Number(5),
LeaveStartDate Date,
LeaveEndDate Date NOT NULL,
LeaveReason Varchar2(50),
LeaveType Char(2) NOT NULL,
CONSTRAINT comp_Key PRIMARY KEY(EmployeeID,LeaveStartDate)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 19
FOREIGN KEY Constraint
• 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.
• Removes the inconsistency in two tables when the data in one table
depends on the data in another table.
• Always refers the primary key column of another table or in the same
table.
Guidelines
• A foreign key value must match an existing value in the parent table or
be NULL.
• Foreign keys are based on data values and are purely logical, rather
than physical pointers.
Copyright © 2009, Oracle. All rights reserved.
9 - 20
DEPARTMENTS
EMPLOYEES
FOREIGN
KEY
INSERT INTO Not allowed
(9 does not
exist)
Allowed
PRIMARY
KEY
…
…
FOREIGN KEY Constraint
Copyright © 2009, Oracle. All rights reserved.
9 - 21
Defining FOREIGN KEY Constraint
CREATE TABLE Department(
DeptNo Number(4) CONSTRAINT dept_pk PRIMARY KEY,
DeptName Varchar2(15) NOT NULL,
Location Varchar2(25) NOT NULL,
);
• Create Department Table
• Column-level Foreign Key constraint:
CREATE TABLE EmpDetails(
EmpCode Number(5) CONSTRAINT emp_pk PRIMARY KEY,
EmpName Varchar2(15) NOT NULL,
Job Varchar2(12),
DeptNo Number(4) CONSTRAINT dept_fk REFERENCES Department(DeptNo),
Salary Number(8,2)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 22
Defining FOREIGN KEY Constraint
• Table-level Foreign Key constraint:
CREATE TABLE EmpDetails(
EmpCode Number(5),
EmpName Varchar2(15) NOT NULL,
Job Varchar2(12),
Salary Number(8,2),
DeptNo Number(4),
CONSTRAINT emp_pk PRIMARY KEY(EmpCode),
CONSTRAINT dept_fk FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 23
Defining FOREIGN KEY Constraint
• Self Reference
CREATE TABLE Employee(
EmpNo Number(5) CONSTRAINT emp_pk PRIMARY KEY,
EmpName Varchar2(15) NOT NULL,
Job Varchar2(12),
Salary Number(8,2),
MgrID Number(5),
DeptNo Number(4),
CONSTRAINT emp_fk FOREIGN KEY(MgrID) REFERENCES Employee,
CONSTRAINT dept_fk FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 24
• FOREIGN KEY: Defines the column in the child table at the
table-constraint level
• REFERENCES: Identifies the table and column in the parent
table
• ON DELETE CASCADE: Deletes the dependent rows in the
child table when a row in the parent table is deleted
• ON DELETE SET NULL: Converts dependent foreign key
values to null
FOREIGN KEY Constraint Keywords
Copyright © 2009, Oracle. All rights reserved.
9 - 25
Defining FOREIGN KEY Constraint with Keyword
CREATE TABLE BatchDetails(
BatchCode Varchar2(6) CONSTRAINT batch_pk PRIMARY KEY,
CrsName Varchar2(15) NOT NULL,
Duration Number(3),
Faculty Varchar2(5),
CONSTRAINT batch_fk FOREIGN KEY(Faculty) REFERENCES Faculty(F_Code)
ON DELETE SET NULL
);
• BatchDetails Table
• Faculty Table
CREATE TABLE Faculty(
F_Code Varchar2(5) CONSTRAINT fac_pk PRIMARY KEY,
F_Name Varchar2(15) NOT NULL,
Exp Number(3),
);
Copyright © 2009, Oracle. All rights reserved.
9 - 26
CREATE TABLE EmpDetails(
EmployeeID Number(5) CONSTRAINT emp_pk PRIMARY KEY,
EmpName Varchar2(15) NOT NULL,
Salary Number(8,2)
);
• EmpInf Table
• EmployeeLeave Table
Create Table EmployeeLeave(
EmployeeID Number(5),
LeaveStartDate Date,
LeaveEndDate Date NOT NULL,
LeaveReason Varchar2(50),
LeaveType Char(2) NOT NULL,
CONSTRAINT comp_Key PRIMARY KEY(EmployeeID,LeaveStartDate),
CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpDetails(EmployeeID)
ON DELETE CASCADE
);
Defining FOREIGN KEY Constraint with Keyword
Copyright © 2009, Oracle. All rights reserved.
9 - 27
• Defines a condition that each row must satisfy
• The following expressions are not allowed:
– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudo
columns
– Calls to SYSDATE, UID, USER, and USERENV functions
– Queries that refer to other values in other rows
..., salary NUMBER(2)
CONSTRAINT emp_salary_min
CHECK (salary > 0),...
CHECK Constraint
• A single column can have multiple CHECK constraints that refer to the
column in its definition.
• There is no limit to the number of CHECK constraints that you can define
on a column.
Copyright © 2009, Oracle. All rights reserved.
9 - 28
Defining CHECK Constraint
• Column-level Check constraint:
Create Table EMPL(
EmpCode Number(5),
EmpName Varchar2(12),
Job Varchar2(15),
Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal>=6000)
);
• Table-level Check constraint:
Create Table Project(
ProjCode Number(5),
EmployeeID Number(5),
Description Varchar2(50),
StartDate Date,
EndDate Date,
CONSTRAINT chk_date CHECK(StartDate<=EndDate)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 29
Defining CHECK Constraint Using IN Operator
Create Table EmployeeLeave(
EmployeeID Number(5),
LeaveStartDate Date,
LeaveEndDate Date NOT NULL,
LeaveReason Varchar2(50),
LeaveType char(2) CONSTRAINT leave_chk CHECK( LeaveType IN('CL','SL','PL') ),
CONSTRAINT comp_key PRIMARY KEY(EmployeeID,LeaveStartDate),
CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpInf(EmployeeID)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 30
Defining CHECK Constraint Using BETWEEN Operator
Create Table EMPL(
EmpCode Number(5),
EmpName Varchar2(12),
Job Varchar2(15),
Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal>=6000 and Bsal<=15000)
(OR)
Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal BETWEEN 6000 AND 15000)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 31
Constraints Example
Create Table EmployeeLeave(
EmployeeID Number(5),
LeaveStartDate Date DEFAULT SYSDATE,
LeaveEndDate Date,
LeaveReason Varchar2(50),
LeaveType Char(2) DEFAULT 'CL',
CONSTRAINT comp_key PRIMARY KEY(EmployeeID,LeaveStartDate),
CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpInf(EmployeeID),
CONSTRAINT leave_chk CHECK(LeaveType IN('CL','SL','PL')),
CONSTRAINT date_chk CHECK(LeaveStartDate<=LeaveEndDate)
);
Copyright © 2009, Oracle. All rights reserved.
9 - 32
Managing Constraints
 Use the ALTER TABLE Statement to:
• Add or Drop a constraint, but not Modify its structure
• Enable or Disable constraints
• Add a NOT NULL constraint by using the MODIFY clause
Adding a Constraint:
ALTER TABLE tablename
ADD [ CONSTRAINT constraint_name ] constraint_type( column_name) ;
Copyright © 2009, Oracle. All rights reserved.
9 - 33
Managing Constraints (Contd.)
• Adding PRIMARY KEY Constraint
• EmpDetails Table
Create Table EmpDetails(
EmpCode Number(5),
EmpName Varchar2(12),
Job Varchar2(15),
Bsal Number(6)
DeptNo Number(5)
);
ALTER TABLE EmplDetails ADD CONSTRAINT empno_pk PRIMARY KEY(Empno);
• Adding FOREIGN KEY Constraint
ALTER TABLE EmplDetails ADD CONSTRAINT deptno_fk
FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo)
Copyright © 2009, Oracle. All rights reserved.
9 - 34
Managing Constraints (Contd.)
• Adding CHECK Constraint
• EmpDetails Table
Create Table EmpDetails(
EmpCode Number(5),
EmpName Varchar2(12),
Job Varchar2(15),
Bsal Number(6)
DeptNo Number(5)
);
ALTER TABLE EmpDetails ADD CONSTRAINT bsal_chk CHECK(Bsal>=8000)
• Adding NOT NULL Constraint by using MODIFY Clause
ALTER TABLE EmpDetails MODIFY EmpName NOT NULL
Copyright © 2009, Oracle. All rights reserved.
9 - 35
Dropping a Constraint
ALTER TABLE tablename
DROP PRIMARY KEY | UNIQUE ( column_name )
CONSTRAINT constraint_name [CASCADE];
Managing Constraints (Contd.)
• Dropping bsal_chk Constraint
To drop a constraint, you can identify the constraint name from the
USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views.
SELECT CONSTRAINT_NAME, TABLE_NAME FROM USER_CONSTRAINTS;
ALTER TABLE EmpDetails DROP CONSTRAINT bsal_chk ;
Copyright © 2009, Oracle. All rights reserved.
9 - 36
Managing Constraints (Contd.)
• Dropping Dependent Constraints
ALTER TABLE EmpDetails DROP CONSTRAINT deptno_fk ;
ALTER TABLE Department DROP PRIMARY KEY ;
(OR)
ALTER TABLE Department DROP CONSTRAINT deptno_pk ;
• Using CASCADE Option
The CASCADE option of the DROP clause causes any dependent
Constraints also to be dropped.
ALTER TABLE Department DROP PRIMARY KEY CASCADE ;
(OR)
ALTER TABLE Department DROP CONSTRAINT deptno_pk CASCADE ;
Copyright © 2009, Oracle. All rights reserved.
9 - 37
Managing Constraints (Contd.)
Disabling Constraints
• Execute the DISABLE clause of the ALTER TABLE statement to deactivate
an integrity constraint.
• Apply the CASCADE option to disable dependent integrity constraints.
ALTER TABLE tablename
DISABLE CONSTRAINT constraint_name [ CASCADE ];
• Disabling a Constraint
ALTER TABLE EmpDetails DISABLE CONSTRAINT bsal_chk ;
• Using CASCADE option
ALTER TABLE Department DISABLE CONSTRAINT deptno_pk CASCADE ;
Copyright © 2009, Oracle. All rights reserved.
9 - 38
Managing Constraints (Contd.)
Enabling Constraints
• Activate an integrity constraint currently disabled in the table.
• A UNIQUE or PRIMARY KEY index is automatically created when you enable
ALTER TABLE tablename
ENABLE CONSTRAINT constraint_name ;
• Enabling a Constraint
ALTER TABLE EmpDetails ENABLE CONSTRAINT bsal_chk ;
Guidelines
• If you enable a constraint, that constraint applies to all the data in the table. All the
data in the table must fit the constraint.
• Enabling a primary key constraint that was disabled with the CASCADE option does
not enable any foreign keys that are dependent upon the primary key.
Copyright © 2009, Oracle. All rights reserved.
9 - 39
Cascading Constraints
• The CASCADE CONSTRAINTS clause is used along with the
DROP TABLE and DROP COLUMN clause.
• The CASCADE CONSTRAINTS clause drops all referential
integrity constraints that refer to the primary and unique keys
defined on the dropped columns.
• The CASCADE CONSTRAINTS clause also drops all multicolumn
constraints defined on the dropped columns.
Copyright © 2009, Oracle. All rights reserved.
9 - 40
Cascading Constraints
Create Table Project(
ProjCode Number(5) CONSTRAINT proj_pk PRIMARY KEY,
Description Varchar2(50),
StartDate Date,
EndDate Date,
CONSTRAINT chk_date CHECK(StartDate<=EndDate)
);
• Consider Project Table
ALTER TABLE Project DROP (ProjCode) ; (Assume ProjCode has Dependencies)
ALTER TABLE Project DROP (StartDate) ;
• An error is returned for the following statements:
• Reason:
o ProjCode Column has Dependencies
o StartDate Column is referenced by multicolum constraint chk_date
o Project Table is a Parent Table
DROP TABLE Project;
Copyright © 2009, Oracle. All rights reserved.
9 - 41
Cascading Constraints
ALTER TABLE Project DROP COLUMN ProjCode CASCADE CONSTRAINTS ;
Dropping Constrained Column
Dropping Parent Table
DROP TABLE Project CASCADE CONSTRAINTS ;
ALTER TABLE Project DROP COLUMN StartDate CASCADE CONSTRAINTS ;
ALTER TABLE Project DROP (ProjCode,StartDate) CASCADE CONSTRAINTS ;
• If all columns referenced by the constraints defined on the dropped columns, then
CASCADE CONSTRAINTS is not required.
• For example consider Employee Table, assuming that no other referential constraints
from other tables refer to column EmpNo,
ALTER TABLE Employee DROP (EmpNo, MgrID) ;
Copyright © 2009, Oracle. All rights reserved.
9 - 42
Viewing Constraints
• After creating a table, you can confirm its existence by issuing a DESCRIBE
command. The only constraint that you can verify is the NOT NULL constraint.
To view all constraints on your table, query the USER_CONSTRAINTS table.
SELECT Constraint_Name, Constraint_Type, Search_Condition, Table_Name
FROM User_Constraints;
Note:
 Constraints that are not named by the table owner receive the system-
assigned constraint name.
 In constraint type, C stands for CHECK, P for PRIMARY KEY, R for referential
integrity, and U for UNIQUE key.
 Notice that the NOT NULL constraint is really a CHECK constraint.
Copyright © 2009, Oracle. All rights reserved.
9 - 43
Viewing Constraints (Contd.)
SELECT Constraint_Name, Column_Name
FROM User_Cons_Columns
WHERE Table_Name = ‘EMPLOYEE’ ;
• Viewing the columns associated with the constraint names.
Copyright © 2009, Oracle. All rights reserved.
9 - 44
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
Violating Constraints
Copyright © 2009, Oracle. All rights reserved.
9 - 45
Violating Constraints
You cannot delete a row that contains a primary key that is
used as a foreign key in another table.
DELETE FROM departments
WHERE department_id = 60;

More Related Content

Similar to Constraints constraints of oracle data base management systems

Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Les11[1]Including Constraints
Les11[1]Including ConstraintsLes11[1]Including Constraints
Les11[1]Including Constraints
siavosh kaviani
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
ARVIND SARDAR
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
Vibrant Technologies & Computers
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
YitbarekMurche
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
gourav kottawar
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
Mukesh Tekwani
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai1
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
DmitryLenev
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
Md. Mahedee Hasan
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
Alex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
Alex Zaballa
 
constraints2100000000000000000000000000000
constraints2100000000000000000000000000000constraints2100000000000000000000000000000
constraints2100000000000000000000000000000
227567
 

Similar to Constraints constraints of oracle data base management systems (20)

Sql commands
Sql commandsSql commands
Sql commands
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Les11[1]Including Constraints
Les11[1]Including ConstraintsLes11[1]Including Constraints
Les11[1]Including Constraints
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
Integrity and security
Integrity and securityIntegrity and security
Integrity and security
 
Sql ch 12 - creating database
Sql ch 12 - creating databaseSql ch 12 - creating database
Sql ch 12 - creating database
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
Check Constraints in MySQL 8.0. Presented at pre-FOSDEM MySQL Day 2020
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Data integrity
Data integrityData integrity
Data integrity
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
constraints2100000000000000000000000000000
constraints2100000000000000000000000000000constraints2100000000000000000000000000000
constraints2100000000000000000000000000000
 
Sql basics
Sql  basicsSql  basics
Sql basics
 

Recently uploaded

Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

Constraints constraints of oracle data base management systems

  • 1. Copyright © 2009, Oracle. All rights reserved. Constraints
  • 2. Copyright © 2009, Oracle. All rights reserved. 9 - 2  While creating tables in a relational database, you must ensure that no one should enter invalid data in it. Therefore, you need to apply certain rules and constraints for columns that specify the kind of data to be stored.  If the checks are not applied while defining and creating tables, the data stored in the tables can become redundant.  Therefore, it is important to ensure that the data stored in tables is complete and consistent. The concept of maintaining consistency and completeness of data is called Data Integrity. Implementing Data Integrity
  • 3. Copyright © 2009, Oracle. All rights reserved. 9 - 3  Data integrity:  Is enforced to ensure that the data in a database is accurate, consistent, and reliable.  Is broadly classified into the following categories:  Entity integrity  Domain integrity  Referential integrity Implementing Data Integrity (Contd.)
  • 4. Copyright © 2009, Oracle. All rights reserved. 9 - 4 Implementing Data Integrity (Contd.) Entity Integrity  Ensures that each row can be uniquely identified by an attribute called the primary key. The primary key column contains unique value in all the rows. In addition, this column cannot be NULL. Domain Integrity  Ensures that only a valid range of values is stored in a column. It can be enforced by restricting the type of data, the range of values, and the format of the data. Referential Integrity  Ensures that the values of the foreign key match the value of the corresponding primary key.
  • 5. Copyright © 2009, Oracle. All rights reserved. 9 - 5 Implementing Data Integrity (Contd.)  Constraints: • Enforce rules that must be followed to maintain consistency and correctness of the data. • Constraints prevent the deletion of a table if there are dependencies. • The following constraint types are valid: – NOT NULL – UNIQUE – PRIMARY KEY – FOREIGN KEY – CHECK Types of Constraints
  • 6. Copyright © 2009, Oracle. All rights reserved. 9 - 6 Guidelines • You can name a constraint, or the Oracle server generates a name with the SYS_Cn format. • Create a constraint at either of the following times: – At the time of creation of table – After the table has been created • Check the existing data if added after the creation of the table • Define a constraint at the column or table level. • View a constraint in the data dictionary. • Can be created by using either of the following statements: CREATE TABLE statement ALTER TABLE statement
  • 7. Copyright © 2009, Oracle. All rights reserved. 9 - 7 • Syntax: CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); column,... [CONSTRAINT constraint_name] constraint_type (column, ...), column [CONSTRAINT constraint_name] constraint_type, Defining Constraints • Column-level constraint: • Table-level constraint: Note NOT NULL constraints must be defined at the column level.
  • 8. Copyright © 2009, Oracle. All rights reserved. 9 - 8 CREATE TABLE Student( Sno Number(5), Sname Varchar2(12), . . . Fees Number(8,2), CONSTRAINT sno_pk PRIMARY KEY(Sno) ); CREATE TABLE Student( Sno Number(5) CONSTRAINT sno_pk PRIMARY KEY, Sname Varchar2(12), Course Varchar2(10), Fees Number(8,2) ); 1 2 Defining Constraints • Column-level constraint: • Table-level constraint:
  • 9. Copyright © 2009, Oracle. All rights reserved. 9 - 9 • Ensures that null values are not permitted for the column: NOT NULL constraint (No row can contain a null value for this column.) Absence of NOT NULL constraint (Any row can contain a null value for this column.) NOT NULL constraint … NOT NULL Constraint
  • 10. Copyright © 2009, Oracle. All rights reserved. 9 - 10 NOT NULL Constraint Columns Data Type Checks EmployeeID Number(5) NOT NULL LeaveStartDate Date NOT NULL LeaveEndDate Date NOT NULL LeaveReason varchar(100) LeaveType Char(2) NOT NULL • Consider the following EmployeeLeave table. CREATE TABLE EmployeeLeave( EmployeeID Number(5) NOT NULL, LeaveStartDate Date NOT NULL. LeaveEndDate Date NOT NULL, LeaveReason Varchar2(15), LeaveType Char(2) NOT NULL );
  • 11. Copyright © 2009, Oracle. All rights reserved. 9 - 11 UNIQUE Constraint • Ensures that every value in a column or set of columns (key) be unique—that is, no two rows of a table can have duplicate values in a specified column or set of columns. • The column (or set of columns) included in the definition of the UNIQUE key constraint is called the unique key. • If the UNIQUE constraint comprises more than one column, that group of columns is called a composite unique key. • UNIQUE constraints enable the input of nulls unless you also define NOT NULL constraints for the same columns. • The Oracle server enforces the UNIQUE constraint by implicitly creating a unique index on the unique key column or columns.
  • 12. Copyright © 2009, Oracle. All rights reserved. 9 - 12 EMPLOYEES UNIQUE constraint INSERT INTO Not allowed: already exists Allowed … UNIQUE Constraint
  • 13. Copyright © 2009, Oracle. All rights reserved. 9 - 13 Defining UNIQUE Constraint CREATE TABLE EmpInf( EmpCode Number(5), EmpName Varchar2(15) NOT NULL, Email Varchar2(25) CONSTRAINT email_unq UNIQUE, Salary Number(8,2) ); • Column-level constraint: • Table-level constraint: CREATE TABLE EmpInf( EmpCode Number(5), . . . Salary Number(8,2), CONSTRAINT email_unq UNIQUE(Email) );
  • 14. Copyright © 2009, Oracle. All rights reserved. 9 - 14 Defining UNIQUE Constraint CREATE TABLE EmpInf( EmpCode Number(5), EmpName Varchar2(15) NOT NULL, Email Varchar2(25) CONSTRAINT email_nn NOT NULL CONSTRAINT email_unq UNIQUE, Salary Number(8,2) ); • More than One Constraint
  • 15. Copyright © 2009, Oracle. All rights reserved. 9 - 15 PRIMARY KEY Constraint • A PRIMARY KEY constraint creates a primary key for the table. Only one primary key can be created for each table. • The PRIMARY KEY constraint is a column or set of columns that uniquely identifies each row in a table. • This constraint enforces uniqueness of the column or column combination and ensures that no column that is part of the primary key can contain a null value. • It is similar to the Unique key constraint except that it does not allow NULLrow.
  • 16. Copyright © 2009, Oracle. All rights reserved. 9 - 16 DEPARTMENTS PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed (50 already exists) … PRIMARY KEY Constraint
  • 17. Copyright © 2009, Oracle. All rights reserved. 9 - 17 Defining PRIMARY KEY Constraint CREATE TABLE Department( DeptNo Number(5) CONSTRAINT dept_pk PRIMARY KEY, DeptName Varchar2(15) NOT NULL, Location Varchar2(25) NOT NULL, ); • Column-level constraint: • Table-level constraint: CREATE TABLE Department( DeptNo Number(5), DeptName Varchar2(15) NOT NULL, Location Varchar2(25) NOT NULL, CONSTRAINT dept_pk PRIMARY KEY(DeptNo) );
  • 18. Copyright © 2009, Oracle. All rights reserved. 9 - 18 Defining PRIMARY KEY Constraint • Composite Primary Key Create Table EmployeeLeave( EmployeeID Number(5), LeaveStartDate Date, LeaveEndDate Date NOT NULL, LeaveReason Varchar2(50), LeaveType Char(2) NOT NULL, CONSTRAINT comp_Key PRIMARY KEY(EmployeeID,LeaveStartDate) );
  • 19. Copyright © 2009, Oracle. All rights reserved. 9 - 19 FOREIGN KEY Constraint • 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. • Removes the inconsistency in two tables when the data in one table depends on the data in another table. • Always refers the primary key column of another table or in the same table. Guidelines • A foreign key value must match an existing value in the parent table or be NULL. • Foreign keys are based on data values and are purely logical, rather than physical pointers.
  • 20. Copyright © 2009, Oracle. All rights reserved. 9 - 20 DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … … FOREIGN KEY Constraint
  • 21. Copyright © 2009, Oracle. All rights reserved. 9 - 21 Defining FOREIGN KEY Constraint CREATE TABLE Department( DeptNo Number(4) CONSTRAINT dept_pk PRIMARY KEY, DeptName Varchar2(15) NOT NULL, Location Varchar2(25) NOT NULL, ); • Create Department Table • Column-level Foreign Key constraint: CREATE TABLE EmpDetails( EmpCode Number(5) CONSTRAINT emp_pk PRIMARY KEY, EmpName Varchar2(15) NOT NULL, Job Varchar2(12), DeptNo Number(4) CONSTRAINT dept_fk REFERENCES Department(DeptNo), Salary Number(8,2) );
  • 22. Copyright © 2009, Oracle. All rights reserved. 9 - 22 Defining FOREIGN KEY Constraint • Table-level Foreign Key constraint: CREATE TABLE EmpDetails( EmpCode Number(5), EmpName Varchar2(15) NOT NULL, Job Varchar2(12), Salary Number(8,2), DeptNo Number(4), CONSTRAINT emp_pk PRIMARY KEY(EmpCode), CONSTRAINT dept_fk FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo) );
  • 23. Copyright © 2009, Oracle. All rights reserved. 9 - 23 Defining FOREIGN KEY Constraint • Self Reference CREATE TABLE Employee( EmpNo Number(5) CONSTRAINT emp_pk PRIMARY KEY, EmpName Varchar2(15) NOT NULL, Job Varchar2(12), Salary Number(8,2), MgrID Number(5), DeptNo Number(4), CONSTRAINT emp_fk FOREIGN KEY(MgrID) REFERENCES Employee, CONSTRAINT dept_fk FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo) );
  • 24. Copyright © 2009, Oracle. All rights reserved. 9 - 24 • FOREIGN KEY: Defines the column in the child table at the table-constraint level • REFERENCES: Identifies the table and column in the parent table • ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted • ON DELETE SET NULL: Converts dependent foreign key values to null FOREIGN KEY Constraint Keywords
  • 25. Copyright © 2009, Oracle. All rights reserved. 9 - 25 Defining FOREIGN KEY Constraint with Keyword CREATE TABLE BatchDetails( BatchCode Varchar2(6) CONSTRAINT batch_pk PRIMARY KEY, CrsName Varchar2(15) NOT NULL, Duration Number(3), Faculty Varchar2(5), CONSTRAINT batch_fk FOREIGN KEY(Faculty) REFERENCES Faculty(F_Code) ON DELETE SET NULL ); • BatchDetails Table • Faculty Table CREATE TABLE Faculty( F_Code Varchar2(5) CONSTRAINT fac_pk PRIMARY KEY, F_Name Varchar2(15) NOT NULL, Exp Number(3), );
  • 26. Copyright © 2009, Oracle. All rights reserved. 9 - 26 CREATE TABLE EmpDetails( EmployeeID Number(5) CONSTRAINT emp_pk PRIMARY KEY, EmpName Varchar2(15) NOT NULL, Salary Number(8,2) ); • EmpInf Table • EmployeeLeave Table Create Table EmployeeLeave( EmployeeID Number(5), LeaveStartDate Date, LeaveEndDate Date NOT NULL, LeaveReason Varchar2(50), LeaveType Char(2) NOT NULL, CONSTRAINT comp_Key PRIMARY KEY(EmployeeID,LeaveStartDate), CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpDetails(EmployeeID) ON DELETE CASCADE ); Defining FOREIGN KEY Constraint with Keyword
  • 27. Copyright © 2009, Oracle. All rights reserved. 9 - 27 • Defines a condition that each row must satisfy • The following expressions are not allowed: – References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudo columns – Calls to SYSDATE, UID, USER, and USERENV functions – Queries that refer to other values in other rows ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),... CHECK Constraint • A single column can have multiple CHECK constraints that refer to the column in its definition. • There is no limit to the number of CHECK constraints that you can define on a column.
  • 28. Copyright © 2009, Oracle. All rights reserved. 9 - 28 Defining CHECK Constraint • Column-level Check constraint: Create Table EMPL( EmpCode Number(5), EmpName Varchar2(12), Job Varchar2(15), Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal>=6000) ); • Table-level Check constraint: Create Table Project( ProjCode Number(5), EmployeeID Number(5), Description Varchar2(50), StartDate Date, EndDate Date, CONSTRAINT chk_date CHECK(StartDate<=EndDate) );
  • 29. Copyright © 2009, Oracle. All rights reserved. 9 - 29 Defining CHECK Constraint Using IN Operator Create Table EmployeeLeave( EmployeeID Number(5), LeaveStartDate Date, LeaveEndDate Date NOT NULL, LeaveReason Varchar2(50), LeaveType char(2) CONSTRAINT leave_chk CHECK( LeaveType IN('CL','SL','PL') ), CONSTRAINT comp_key PRIMARY KEY(EmployeeID,LeaveStartDate), CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpInf(EmployeeID) );
  • 30. Copyright © 2009, Oracle. All rights reserved. 9 - 30 Defining CHECK Constraint Using BETWEEN Operator Create Table EMPL( EmpCode Number(5), EmpName Varchar2(12), Job Varchar2(15), Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal>=6000 and Bsal<=15000) (OR) Bsal Number(6) CONSTRAINT sal_chk CHECK(Bsal BETWEEN 6000 AND 15000) );
  • 31. Copyright © 2009, Oracle. All rights reserved. 9 - 31 Constraints Example Create Table EmployeeLeave( EmployeeID Number(5), LeaveStartDate Date DEFAULT SYSDATE, LeaveEndDate Date, LeaveReason Varchar2(50), LeaveType Char(2) DEFAULT 'CL', CONSTRAINT comp_key PRIMARY KEY(EmployeeID,LeaveStartDate), CONSTRAINT empid_fk FOREIGN KEY(EmployeeID) REFERENCES EmpInf(EmployeeID), CONSTRAINT leave_chk CHECK(LeaveType IN('CL','SL','PL')), CONSTRAINT date_chk CHECK(LeaveStartDate<=LeaveEndDate) );
  • 32. Copyright © 2009, Oracle. All rights reserved. 9 - 32 Managing Constraints  Use the ALTER TABLE Statement to: • Add or Drop a constraint, but not Modify its structure • Enable or Disable constraints • Add a NOT NULL constraint by using the MODIFY clause Adding a Constraint: ALTER TABLE tablename ADD [ CONSTRAINT constraint_name ] constraint_type( column_name) ;
  • 33. Copyright © 2009, Oracle. All rights reserved. 9 - 33 Managing Constraints (Contd.) • Adding PRIMARY KEY Constraint • EmpDetails Table Create Table EmpDetails( EmpCode Number(5), EmpName Varchar2(12), Job Varchar2(15), Bsal Number(6) DeptNo Number(5) ); ALTER TABLE EmplDetails ADD CONSTRAINT empno_pk PRIMARY KEY(Empno); • Adding FOREIGN KEY Constraint ALTER TABLE EmplDetails ADD CONSTRAINT deptno_fk FOREIGN KEY(DeptNo) REFERENCES Department(DeptNo)
  • 34. Copyright © 2009, Oracle. All rights reserved. 9 - 34 Managing Constraints (Contd.) • Adding CHECK Constraint • EmpDetails Table Create Table EmpDetails( EmpCode Number(5), EmpName Varchar2(12), Job Varchar2(15), Bsal Number(6) DeptNo Number(5) ); ALTER TABLE EmpDetails ADD CONSTRAINT bsal_chk CHECK(Bsal>=8000) • Adding NOT NULL Constraint by using MODIFY Clause ALTER TABLE EmpDetails MODIFY EmpName NOT NULL
  • 35. Copyright © 2009, Oracle. All rights reserved. 9 - 35 Dropping a Constraint ALTER TABLE tablename DROP PRIMARY KEY | UNIQUE ( column_name ) CONSTRAINT constraint_name [CASCADE]; Managing Constraints (Contd.) • Dropping bsal_chk Constraint To drop a constraint, you can identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary views. SELECT CONSTRAINT_NAME, TABLE_NAME FROM USER_CONSTRAINTS; ALTER TABLE EmpDetails DROP CONSTRAINT bsal_chk ;
  • 36. Copyright © 2009, Oracle. All rights reserved. 9 - 36 Managing Constraints (Contd.) • Dropping Dependent Constraints ALTER TABLE EmpDetails DROP CONSTRAINT deptno_fk ; ALTER TABLE Department DROP PRIMARY KEY ; (OR) ALTER TABLE Department DROP CONSTRAINT deptno_pk ; • Using CASCADE Option The CASCADE option of the DROP clause causes any dependent Constraints also to be dropped. ALTER TABLE Department DROP PRIMARY KEY CASCADE ; (OR) ALTER TABLE Department DROP CONSTRAINT deptno_pk CASCADE ;
  • 37. Copyright © 2009, Oracle. All rights reserved. 9 - 37 Managing Constraints (Contd.) Disabling Constraints • Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. • Apply the CASCADE option to disable dependent integrity constraints. ALTER TABLE tablename DISABLE CONSTRAINT constraint_name [ CASCADE ]; • Disabling a Constraint ALTER TABLE EmpDetails DISABLE CONSTRAINT bsal_chk ; • Using CASCADE option ALTER TABLE Department DISABLE CONSTRAINT deptno_pk CASCADE ;
  • 38. Copyright © 2009, Oracle. All rights reserved. 9 - 38 Managing Constraints (Contd.) Enabling Constraints • Activate an integrity constraint currently disabled in the table. • A UNIQUE or PRIMARY KEY index is automatically created when you enable ALTER TABLE tablename ENABLE CONSTRAINT constraint_name ; • Enabling a Constraint ALTER TABLE EmpDetails ENABLE CONSTRAINT bsal_chk ; Guidelines • If you enable a constraint, that constraint applies to all the data in the table. All the data in the table must fit the constraint. • Enabling a primary key constraint that was disabled with the CASCADE option does not enable any foreign keys that are dependent upon the primary key.
  • 39. Copyright © 2009, Oracle. All rights reserved. 9 - 39 Cascading Constraints • The CASCADE CONSTRAINTS clause is used along with the DROP TABLE and DROP COLUMN clause. • The CASCADE CONSTRAINTS clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns. • The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on the dropped columns.
  • 40. Copyright © 2009, Oracle. All rights reserved. 9 - 40 Cascading Constraints Create Table Project( ProjCode Number(5) CONSTRAINT proj_pk PRIMARY KEY, Description Varchar2(50), StartDate Date, EndDate Date, CONSTRAINT chk_date CHECK(StartDate<=EndDate) ); • Consider Project Table ALTER TABLE Project DROP (ProjCode) ; (Assume ProjCode has Dependencies) ALTER TABLE Project DROP (StartDate) ; • An error is returned for the following statements: • Reason: o ProjCode Column has Dependencies o StartDate Column is referenced by multicolum constraint chk_date o Project Table is a Parent Table DROP TABLE Project;
  • 41. Copyright © 2009, Oracle. All rights reserved. 9 - 41 Cascading Constraints ALTER TABLE Project DROP COLUMN ProjCode CASCADE CONSTRAINTS ; Dropping Constrained Column Dropping Parent Table DROP TABLE Project CASCADE CONSTRAINTS ; ALTER TABLE Project DROP COLUMN StartDate CASCADE CONSTRAINTS ; ALTER TABLE Project DROP (ProjCode,StartDate) CASCADE CONSTRAINTS ; • If all columns referenced by the constraints defined on the dropped columns, then CASCADE CONSTRAINTS is not required. • For example consider Employee Table, assuming that no other referential constraints from other tables refer to column EmpNo, ALTER TABLE Employee DROP (EmpNo, MgrID) ;
  • 42. Copyright © 2009, Oracle. All rights reserved. 9 - 42 Viewing Constraints • After creating a table, you can confirm its existence by issuing a DESCRIBE command. The only constraint that you can verify is the NOT NULL constraint. To view all constraints on your table, query the USER_CONSTRAINTS table. SELECT Constraint_Name, Constraint_Type, Search_Condition, Table_Name FROM User_Constraints; Note:  Constraints that are not named by the table owner receive the system- assigned constraint name.  In constraint type, C stands for CHECK, P for PRIMARY KEY, R for referential integrity, and U for UNIQUE key.  Notice that the NOT NULL constraint is really a CHECK constraint.
  • 43. Copyright © 2009, Oracle. All rights reserved. 9 - 43 Viewing Constraints (Contd.) SELECT Constraint_Name, Column_Name FROM User_Cons_Columns WHERE Table_Name = ‘EMPLOYEE’ ; • Viewing the columns associated with the constraint names.
  • 44. Copyright © 2009, Oracle. All rights reserved. 9 - 44 UPDATE employees SET department_id = 55 WHERE department_id = 110; Violating Constraints
  • 45. Copyright © 2009, Oracle. All rights reserved. 9 - 45 Violating Constraints You cannot delete a row that contains a primary key that is used as a foreign key in another table. DELETE FROM departments WHERE department_id = 60;