0% found this document useful (0 votes)
8 views

SQL Tutorial (Chap5)

Uploaded by

jaggu011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SQL Tutorial (Chap5)

Uploaded by

jaggu011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

 Chapter 5: Constraints

SQL Tutorial - What are Constraints?


 Constraint is a rule or restriction which is imposed on the table data.

 For a new table, Constraints can be specified in the create table syntax.

 For an existing table in the database, Constraints can be added by alter table syntax.

 Constraints are used to enforce business rules on data.

Why constraints are required?


 We use constraints, if we want to enforce rules whenever a row is inserted, updated or deleted from
that table. i.e. For every operation on the table data to succeed, constraint must be satisfied first.

 To prevent the deletion of a table data if it has dependencies on other tables.

 Allow or restrict null values.

 Ensure unique values for columns.

 Ensure a primary identifying value for each row in a table.

Constraints are categorized as follows.

Domain integrity constraints

 Not null

 Check

Entity integrity constraints

 Unique

 Primary key

Referential integrity constraints


 Foreign key

There are three different ways to add constraints:


 Column level – along with the column definition
 Table level – after the table definition
 Alter level – using alter command

Whatever is the way we choose (Column level / Table level / alter level), Constraints are always
attached to a column not to a table.

Constraint names:

 Constraint names must be unique to the owner.


 The constraint name appears in messages when the constraint is violated.
 If a constraint name is not specified, the Oracle Server assigns a unique name with the format
SYS_C00n.
 A suggested format for naming a constraint is

“TABLENAME_CONSTRAINT TYPE_COLNAME” example:- EMP_NN_SAL.


While adding constraints we need not specify the name, oracle will internally generate the name
of the constraint.

If we want to give a name to the constraint then we have to use the constraint clause along
with constraint name.
System tables for viewing constraints:-
 user_constraints:-
Information about columns in constraint definitions
Owned by the user

 all_constraints:-
Constraint definitions on accessible tables.
 dba_constraints:-
Constraint definitions on all tables.

SQL Tutorial - Not Null - Constraint

 ‘NOT NULL’ constraints are used to avoid null values for a specific column.
 We can add ‘NOT NULL’ constraint at column level only.
 Columns without the ‘NOT NULL’ constraint allow NULL values. (i.e. if no value is specified then NULL is
the default) .

If Constraint name is not specified then system will generate a unique name for the constraint.
Constraint without name

SQL>CREATE TABLE emp (empno NUMBER NOT NULL,


ename VARCHAR2 (100),
sal NUMBER (5));
If we want to give a name to the constraint, we have to use the constraint clause.

Constraint with name

SQL>CREATE TABLE emp (empno NUMBER CONSTRAINT emp_nn NOT NULL,


ename VARCHAR2 (100),
sal NUMBER (5));

By using below query we can know the name of the constraint attached to a particular a table.

SQL>SELECT constraint_name,
constraint_type,
search_condition
FROM user_constraints
WHERE TABLE_NAME='EMP';

Test Constraint:-

Suppose if we try to insert null values into table column which has NOTNULL constraint then system
will raise an error.

SQL> INSERT INTO emp (empno, ename, sal)


VALUES (NULL,'MARK', 2000);
Output:
ERROR at line 1:

ORA-01400: cannot INSERT NULL into ("EMP"."EMPNO")

SQL Tutorial - Check - Constraint


Check constraint is used to insert the values based on specified condition. The Check constraint
explicitly defines a condition that each row must satisfy.

We can add this constraint in all three levels.


 Column level
 Table level
 Alter level
COLUMN LEVEL
In the below example we are trying to add a check constraint on salary (i.e. we are allowed to
insert a record only if salary is greater than 10000).

Note: If we do not specify name for the constraint then system will automatically assign a
system generated name.
constraint without name
SQL>CREATE TABLE emp (empno NUMBER,
sal NUMBER (5) CHECK (sal<10000),
ename VARCHAR2 (100));
We can specify the constraint name along with the constraint clause.

constraint with name


SQL>CREATE TABLE emp (empno NUMBER,
sal NUMBER (5) CONSTRAINT emp_ck CHECK (sal<10000),
name VARCHAR2 (100));

TABLE LEVEL
constraint without name
SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
CHECK (sal<10000));

constraint with name


SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
CONSTRAINT emp_ck CHECK (sal<10000));

ALTER LEVEL
We can add constraint to an existing table by using alter command.
SQL> ALTER TABLE emp ADD CONSTRAINT emp_ch CHECK (sal<10000)

TABLE altered.
To drop a constraint from the existing table:
SQL> ALTER TABLE emp DROP CONSTRAINT emp_ch CHECK (sal<10000);

-- Table altered.

Test Constraint:-
If we try to insert the ‘sal’ above 10000 then system will raise an error.
SQL> INSERT INTO emp (empno, ename, sal) VALUES (6788,'SQL', 11000);

INSERT INTO emp (empno, ename, sal) VALUES (6788,'SQL', 11000)


*
ERROR at line 1:
ORA-02290: CHECK CONSTRAINT (SCOTT.EMP_CH) violated

SQL Tutorial - Unique - Constraint


Unique constraint is used to avoid duplicates values in the column data but it allows null values.

We use unique constraint to ensure that our table column has unique information.

We can add this constraint in all three levels

 Column Level
 Table Level
 Alter Level.

Note :- Whatever is the level we add a constraint, impact remains the same. Constraint always
gets assigned to the column level.

COLUMN LEVEL
If we do not specify name for the constraint then system will automatically assign a system
generated name.
Constraint without name
SQL>CREATE TABLE emp1 (empno NUMBER UNIQUE,
ename VARCHAR2 (100),
sal UMBER (5));
We can specify the constraint name when defining a constraint.

Constraint with name


SQL>CREATE TABLE emp2 (empno NUMBER CONSTRAINT emp_ck UNIQUE,
ename VARCHAR2 (100),
Sal NUMBER (5));

TABLE LEVEL
Constraint without name
SQL>CREATE TABLE emp3 (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
UNIQUE (empno)
);
Constraint with name
SQL>CREATE TABLE emp4 (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
CONSTRAINT emp_un UNIQUE (empno));

ALTER LEVEL
We can add constraint to an existing table using alter command.
SQL> ALTER TABLE emp ADD CONSTRAINT emp_un UNIQUE (empno);

-- Table altered.
To drop a constraint:
SQL> ALTER TABLE emp DROP CONSTRAINT emp_un UNIQUE (empno);

-- Table altered.
Test Constraint:-
If we try to insert an employee record with already existing ‘empno’ then system will raise an
error.
SQL> INSERT INTO emp (empno, ename, sal)
VALUES (7788,'SQL', 3000);
Output:
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.EMP_UN) violated

However as it is unique constraint, system will allow null values.


SQL> INSERT INTO emp (empno, ename, sal)
VALUES (NULL,'SQL', 1000);

1 ROW created.

SQL Tutorial - Primary Key - Constraint



Primary Key is used to avoid duplicates and nulls. This constraint will work as a combination of
both unique and not null.
 Only one primary key is allowed to a table.
 For parent child relationships across tables, Primary key is always attached to the parent table.
 If we want more than one column to work as Primary Key columns then those are called
composite primary key.
 Note that we can take a maximum of 32 columns in composite primary key and these composite
primary key can be declared only at Table level.
 We can add this constraint in all three levels.
o Column Level
o Table Level
o Alter Level

Note: Whatever is the level we add a constraint, impact remains the same. Constraint always
gets assigned to the column level.

COLUMN LEVEL
If we do not specify name for the constraint then system will automatically assign a system
generated name.

constraint without name


SQL>CREATE TABLE emp1 (empno NUMBER PRIMARY KEY,
ename VARCHAR2 (100),
sal NUMBER (5));
Here we mention the Constraint clause along with constraint name.

Constraint with name


SQL>CREATE TABLE emp2 (empno NUMBER CONSTRAINT emp_pk PRIMARY KEY,
ename VARCHAR2 (100),
sal NUMBER (5));

TABLE LEVEL
CONSTRAINT without name
SQL>CREATE TABLE emp3 (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
PRIMARY KEY (empno));

Here we mention the Constraint clause along with constraint name in column level.
Constraint with name
SQL>CREATE TABLE emp4 (empno NUMBER,
CONSTRAINT emp_pk PRIMARY KEY (empno),
ename VARCHAR2 (100),
sal NUMBER (5));

COMPOSITE PRIMARY KEY

SQL>CREATE TABLE employee (empno NUMBER(5),


name varchar2(20),
address varchar2(20),
PRIMARY KEY(empno,name);
ALTER LEVEL
We can add constraint to an existing table by using alter command.

Constraint without name


SQL> ALTER TABLE emp1 ADD PRIMARY KEY (empno);

TABLE altered.

constraint with name


SQL> ALTER TABLE emp2 ADD CONSTRAINT emp_pk PRIMARY KEY (empno);

TABLE altered.
To drop a constraint:
SQL> ALTER TABLE emp2 DROP CONSTRAINT emp_pk PRIMARY KEY (empno);

-- Table altered.

Test Constraint:-
From the above commands let’s assume we have primary key constraint on ‘empno’ column.
If we try to insert an employee record with already existing ‘empno’ then system will raise an
error.
SQL> INSERT INTO emp1 (empno, ename, sal) VALUES (7788,'MARK', 3000);
Output:
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.EMP_UN) violated

Even NULL values are not allowed as constraint added is ‘Primary Key’.
SQL> INSERT INTO emp1 (empno, ename, sal) VALUES (NULL,'MARK', 2000);
Output:
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."EMP"."EMPNO").

SQL Tutorial - Foreign Key - Constraint

 Foreign keys are used to refer the parent table primary key column which does not allow
duplicates.
 The Foreign key constraint provides referential integrity rules (either within a table or between
tables).
i.e. We can only place a value in TABLE B if the values exist as a primary key in TABLE A.
 For parent child relationships across tables, foreign key is always attached to the child table.
 We use foreign key if we want to ensure that for every child table record there is a reference in
parent table.
 We can add this constraint in all three levels.

 Column Level
 Table Level
 Alter Level

To demonstrate foreign key constraint we need parent child relationship between the tables.
Let’s first create the parent/master table (i.e DEPT table) and make deptno column as primary
key column.

SQL>CREATE TABLE dept (deptno NUMBER (2) PRIMARY KEY,


dname VARCHAR2 (10),
loc VARCHAR2 (10));

TABLE created.

COLUMN LEVEL
Based on the parent/master table (DEPT) now let’s create child table (i.e. EMP table) and assign
the foreign key for the deptno column as shown in below.
SQL> CREATE TABLE emp (empno NUMBER (4),
ename VARCHAR2 (10),
sal NUMBER (5),
deptno NUMBER (2) REFERENCES dept(deptno));

TABLE created.

Constraint with name


SQL> CREATE TABLE emp (empno NUMBER (4),
ename VARCHAR2 (10),
sal NUMBER (5),
deptno NUMBER (2) CONSTRAINT emp_dept_fk REFERENCES dept(deptno));

TABLE created.

TABLE LEVEL
We can add foreign constraint at table level.

constraint without name


SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
deptno NUMBER,
FOREIGN KEY (deptno) REFERENCES dept (deptno));
We can specify the constraint name when defining the constraint.

Constraint with name


SQL>CREATE TABLE emp (empno NUMBER,
Ename VARCHAR2 (100),
sal NUMBER (5),
deptno NUMBER,
CONSTRAINT emp_dept_fk FOREIGN KEY (deptno) REFERENCES dept (deptno));

ALTER LEVEL
We can add constraint to an existing table by using alter command.

constraint without name


SQL> ALTER TABLE emp ADD FOREIGN KEY (deptno) REFERENCES dept (deptno);

TABLE altered.
Here we mention constraint name along with constraint clause.

Constraint with name


SQL> ALTER TABLE emp ADD CONSTRAINT emp_dept_fk FOREIGN KEY (deptno) REFERENCES dept (deptno)

TABLE altered.
Once the primary key and foreign key relationship has been created then we can not remove any
parent record if there are dependent records in the child table.

To drop a constraint:
SQL> ALTER TABLE emp DROP CONSTRAINT emp_dept_fk FOREIGN KEY (deptno) REFERENCES dept (deptno

-- Table altered.

Test Constraint:-
From the above example we have created a relationship among the tables EMP and DEPT
SQL>SELECT * FROM dept;

SQL>SELECT * FROM emp;


Now if we try to insert the values into “emp” table with deptno=60 (which is not avilable in
parent table) then system will raise an error
SQL> INSERT INTO emp (empno, ename, deptno) VALUES (3578,'MARK', 60);
Output:
ERROR at line 1:
ORA-02291: integrity constraint (APPS.EMP_FK) violated - parent key not found

ON Delete Cascade
‘ON DELETE CASCADE’ is an extension to ‘Foreign key’ constraint. If a parent-child relationship
(foreign key relationship) exists between the tables then we will not be able delete the parent
record when child exists for it. (i.e. we cannot delete Deptno = 10 record from DEPT table when
there are employees available in EMP table for Deptno = 10 ).

By using ‘ON DELETE CASCADE’ clause we can remove the parent record even it Childs exists.
Because with ‘ON DELETE CASCADE’ whenever you remove parent record system automatically
removes all its dependent records from child table.

‘ON DELETE CASCADE’ clause should be used when defining the foreign key constraint in the
child table.

We can define this at all three levels

 Column Level
 Table Level
 Alter Level
To demonstrate foreign key constraint we need parent child relationship between the tables.
Let’s first create the parent/master table (i.e DEPT table) and make deptno column as primary
key column.

SQL> CREATE TABLE dept (deptno NUMBER (2) PRIMARY KEY,


dname VARCHAR2 (10),
loc VARCHAR2 (10));

Output:-

TABLE created.

COLUMN LEVEL
Based on the parent/master table (DEPT) now let’s create child table (i.e. EMP table) and assign
the foreign key for the deptno column as shown in below.
When assigning foreign key, add key word ‘ON DELETE CASCADE’ in the end. This will ensure that
child records will be deleted when deleting a parent record.
If we don’t use ‘On DELETE CASCADE’ command then we will not be able to delete the parent
records at all.
Constraint without name
SQL> CREATE TABLE emp (empno NUMBER (4),
ename VARCHAR2 (10),
sal NUMBER (5),
deptno NUMBER (2) REFERENCES dept(deptno) ON DELETE CASCADE) ;

Output:-

TABLE created.

constraint with name


SQL> CREATE TABLE emp (empno NUMBER (4),
ename VARCHAR2 (10),
sal NUMBER (5),
deptno NUMBER (2) CONSTRAINT emp_dept_fk REFERENCES dept(deptno) ON DELETE CASCADE);

Output:-

TABLE created.

TABLE LEVEL
We can add foreign constraint at table level.

constraint without name


SQL>CREATE TABLE emp (empno NUMBER PRIMARY KEY,
ename VARCHAR2 (100),
sal NUMBER (5),
deptno NUMBER,
FOREIGN KEY (deptno) REFERENCES dept (deptno) ON DELETE CASCADE);

We can specify the constraint name when defining the constraint


Constraint with name
SQL> CREATE TABLE emp (empno NUMBER PRIMARY KEY,
ename VARCHAR2 (100),
sal NUMBER (5),
deptno NUMBER,
CONSTRAINT emp_dept_fk FOREIGN KEY (deptno) REFERENCES dept (deptno) ON DELETE CASCADE);

ALTER LEVEL
We can add constraint to an existing table using alter command.

Constraint without name


SQL> ALTER TABLE emp ADD FOREIGN KEY (deptno) REFERENCES dept (deptno) ON DELETE CASCADE;

TABLE altered.

Constraint with name


SQL> ALTER TABLE emp ADD CONSTRAINT emp_dept_fk FOREIGN KEY (deptno)
REFERENCES dept (deptno) ON DELETE CASCADE;

Output:-

TABLE altered.

Test Constraint:-
From the above commands, let’s assume we now have a ‘foreign key’ relationship between EMP
and DEPT table with ‘ON DELETE CASCADE’.
SQL>SELECT * FROM dept;

SQL>SELECT * FROM emp;


Now lets try to delete the record from master table (Deptno = 10 from DEPT table) and check
whether corresponding child records get deleted or not.
SQL> DELETE FROM dept
WHERE deptno=10;

/* Now Issue the commit */

SQL> Commit;
SQL> SLECT * FROM dept;

/* Parent record is deleted, let’s check the child table */


SQL> SELECT * FROM emp;
/* from the output we can observe that all the employee records whose deptno is 10 in EMP table
are deleted automatically */

SQL Tutorial - Composite Keys


 A composite key is a constraint that is created on combination of columns.
 Composite key can be defined in table and alter levels only. (no column level)
 Composite key is not a system keyword, it is just a name given to the constraints which are
created on multiple columns of a table.
Example: like creating a primary key constraint on both EMPNO and ENAME columns of EMP
table. (i.e. data combination of both columns EMPNO and ENAME should be unique across the
table)
 We can define composite keys on entity integrity and referential integrity constraints.

Composite Unique key:


TABLE LEVEL
Here we are trying to create a composite unique constraint at table level and if we don’t specify
the name system will automatically generate the name.

constraint without name


SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
UNIQUE (empno, ename));

Constraint with name


SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
CONSTRAINT emp_cmp_un UNIQUE (empno, ename));

ALTER LEVEL
We use alter command if we wanted to add a composite key for an existing table.

Constraint without name


SQL> ALTER TABLE emp ADD UNIQUE (empno, ename)

TABLE altered.
Constraint with name
SQL> ALTER TABLE emp ADD CONSTRAINT emp_cmp_un UNIQUE (empno, ename)

TABLE altered.

Test constraint:-
Now let’s test the unique composite constraint.
i.e. UNIQUE (empno, ename)
SQL>SELECT * FROM emp;

Let’s try to insert the values empno=7369 and ename = ‘SMITH’ into emp table which are
already available in table.
This scenario will trigger the UNIQUE constraint error.
SQL> INSERT INTO emp (empno, ename, deptno) VALUES (7369,'SMITH', 30);
Output:
ERROR at line 1:
ORA-00001: unique constraint (APPS.EMP_CMP_UN) violated
Composite Primary key :
Just as above, we can add composite constraint to the table using Primary key.

TABLE LEVEL
Here we are trying to create a composite primary constraint at table level and if we don’t specify
the name system will automatically generate the name.

Constraint without name


SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
PRIMARY KEY (empno, ename));
Constraint with name
SQL>CREATE TABLE emp (empno NUMBER,
ename VARCHAR2 (100),
sal NUMBER (5),
CONSTRAINT emp_cmp_pk PRIMARY KEY (empno, ename));

ALTER LEVEL
We use alter command if we wanted to add a composite key for an existing table.

Constraint without name


SQL> ALTER TABLE emp ADD PRIMARY KEY (empno, ename);

TABLE altered.
Constraint with name
SQL> ALTER TABLE emp ADD CONSTRAINT emp_cmp_pk PRIMARY KEY (empno, ename);

TABLE altered.

Test constraint:-
Now let’s test the primary key composite constraint.
i.e. PRIMARY KEY (empno, ename)
Example remains same as unique constraint but in Primary key system does not allow null where
as unique constraint allows null.
SQL>SELECT * FROM emp;
Let’s try to insert the values empno=7369 and ename = ‘SMITH’ into emp table which are
already available in table.
This scenario will trigger the PRIMARY KEY constraint error.
SQL> INSERT INTO emp (empno, ename, deptno) VALUES (7369,'SMITH', 30);
Output:
ERROR at line 1:
ORA-00001: unique constraint (APPS.EMP_CMP_PK) violated

You might also like