0% found this document useful (0 votes)
10 views33 pages

Constraints

The document provides an overview of SQL constraints in Oracle, detailing their purpose in ensuring data accuracy and reliability within tables. It categorizes constraints into column level and table level, and explains various types such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT constraints, along with their usage and examples. Additionally, it discusses the concept of referential integrity and how foreign keys maintain relationships between tables.

Uploaded by

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

Constraints

The document provides an overview of SQL constraints in Oracle, detailing their purpose in ensuring data accuracy and reliability within tables. It categorizes constraints into column level and table level, and explains various types such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT constraints, along with their usage and examples. Additionally, it discusses the concept of referential integrity and how foreign keys maintain relationships between tables.

Uploaded by

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

Constraints in Oracle

SQL constraints are used to specify rules for the data in a table.
• Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
• Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE
statement.
Constraints in SQL can be categorized into two types:
• Column Level Constraint:
Column Level Constraint is used to apply a constraint on a single column.
• Table Level Constraint:
Table Level Constraint is used to apply a constraint on multiple columns.
Some of the real-life examples of constraints are as
follows:

• Every person has a unique email id. This simply means that no two
users can have the same email ids on the same email providing
service.
• Whenever we set a password for any system, there are certain
constraints that are to be followed. These constraints may include the
following:
• There must be one uppercase character in the password.
• Password must be of at least eight characters in length.
• Password must contain at least one special symbol.
The following constraints are
commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between
tables
• CHECK - Ensures that the values in a column satisfies a specific
condition
• DEFAULT - Sets a default value for a column if no value is specified
1. NOT NULL

• NULL means empty, i.e., the value is not available.


• Whenever a table's column is declared as NOT NULL, then the value
for that column cannot be empty for any of the table's records.
• There must exist a value in the column to which the NOT NULL
constraint is applied.
• NOTE: NULL does not mean zero. NULL means empty column, not
even zero.
Not Null column level constraint :

CREATE TABLE TableName


(ColumnName1 datatype NOT NULL,
ColumnName2 datatype,….,
ColumnNameN datatype);

• Example:
CREATE TABLE student
(StudentID number(4) NOT NULL,
Student_Name varchar2(20));

Desc student
Create NOT NULL constraint - Using
an ALTER TABLE statement
Syntax
ALTER TABLE table_name
MODIFY(column1 NOT NULL);

Example
ALTER TABLE mytable
MODIFY (mynumber NUMBER(4) NOT NULL);
2. UNIQUE Constraint

• Duplicate values are not allowed in the columns to which the UNIQUE
constraint is applied.
• The column with the unique constraint will always contain a unique value.
• This constraint can be applied to one or more than one column of a table,
which means more than one unique constraint can exist on a single table.
• Using the UNIQUE constraint, you can also modify the already created
tables.
CREATE TABLE Persons (
ID number(4) NOT NULL UNIQUE, // column level
LastName varchar2(25) NOT NULL,
FirstName varchar2(25),
Age number(2)
)

CREATE TABLE supplier


( supplier_id number(10) NOT NULL,
supplier_name varchar2(50) NOT NULL,
contact_name varchar2(50),
CONSTRAINT supplier_unique UNIQUE (supplier_id) //Table level
)
Create unique contraint - Using an
ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ...
column_n);

Example
ALTER TABLE supplier
ADD CONSTRAINT supplier_unique UNIQUE (supplier_id);
3. PRIMARY KEY

• PRIMARY KEY Constraint is a combination of NOT NULL and Unique


constraints.
• NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY
constraint.
• The column to which we have applied the primary constraint will always
contain a unique value and will not allow null values.
• A primary key can be defined in either a CREATE TABLE statement or an
ALTER TABLE statement.
At table level :
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
);
CREATE TABLE Persons (
ID number(5) ,
LastName varchar2(25) NOT NULL,
FirstName varchar2(25),
Age number(2),
CONSTRAINT PK_Person PRIMARY KEY (ID)
);
At Column level :

CREATE TABLE TableName


(ColumnName1 datatype PRIMARY KEY,
ColumnName2 datatype,….
ColumnNameN datatype);

Example:
CREATE TABLE Persons
(
ID number(5) PRIMARY KEY,
LastName varchar2(25) NOT NULL,
FirstName varchar2(25),
Age number(2)
What is Composite Key in Oracle?
• Primary key is a column that uniquely identifies column in a table. But sometimes it happens
that a single column is not sufficient to identify tuples in a table. This is where Composite key
comes into consideration. Using two or more column as a Primary key so as to make it unique
• For example, we have Subject ID, that can never be considered as Primary key if we have lot of
student having same subject. But, it will work if we consider Student ID as well as Subject ID
together as a Primary key. It will be nothing but a composite key.
create table stud
(
Name varchar2(20),
Section Varchar2(10),
Roll_no Number (20) ,
Subject_ID Number(20),
Subject Varchar2(20),
PRIMARY KEY(Roll_no,Subject_ID)
);
CREATE TABLE supplier
(
supplier_id number(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
In this example, we've created a primary key on the supplier table called supplier_pk. It
consists of only one field - the supplier_id field.

We could also create a primary key with more than one field as in the example below:

CREATE TABLE supplier


(
supplier_id number(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)
);
Create Primary Key - Using ALTER TABLE statement
You can create a primary key in Oracle with the ALTER TABLE statement.
Syntax:-
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n);

Example
ALTER TABLE supplier
ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id);

In this example, we've created a primary key on the existing supplier table called supplier_pk. It
consists of the field called supplier_id.

We could also create a primary key with more than one field as in the example below:

ALTER TABLE supplier


ADD CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name);
Drop Primary Key
You can drop a primary key in Oracle using the ALTER TABLE statement.

Syntax:

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

Example
Let's look at an example of how to drop a primary key using the ALTER TABLE
statement in Oracle.

ALTER TABLE supplier


DROP CONSTRAINT supplier_pk;
4. Check Constraints

• A check constraint allows you to specify a condition on each row in a table.


• A check constraint can be defined in either a SQL CREATE TABLE statement or a
SQL ALTER TABLE statement.

Using a CREATE TABLE statement


CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
CONSTRAINT constraint_name CHECK (column_name condition)
);
CREATE TABLE suppliers
(
supplier_id number(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);
create table Machine2
(Mid varchar2(6) ,
MName varchar2(10) NOT NULL check (MName= upper(MName)),
MType varchar2(10) CHECK (MType IN (‘drilling’, ‘milling’, ‘lathe’, ‘turning’,
‘grinding’')),
MPrice number(6) check(MPrice>0),
MCost number(6),constraint fp check(MCost<MPrice));
CREATE TABLE myTable
(policy_id NUMBER(4),
holder_name VARCHAR2(40) ,
gender VARCHAR2(1) CHECK(gender in ('M','F')) ,
marital_status VARCHAR2(1) ,
date_of_birth DATE ,
constraint chk_marital CHECK (marital_status in ('S' ,'M' ,'D' ,'W')) );
5. Default Constraint
• As the name suggests the DEFAULT Constraint in Oracle is used to set
a default value for a data column. If the value for the column in the
data row is not specified, the default value will be added to the data
row column. In simple words, we can say that Default constraints are
used to insert a default value to a column when the user doesn’t
specify a value.
CREATE TABLE Employee (
ID NUMBER(4) NOT NULL,
Name VARCHAR2(20) NOT NULL,
Age NUMBER(2),
Country VARCHAR2(10) DEFAULT 'INDIA',
DOJ DATE DEFAULT SYSDATE
);
As you can see in the above CREATE table statement, here, we created the
Country and DOJ columns with the Default Constraint. So, while inserting the
data into the Employee table, if the user does not specify the values for the
Country column, then the default value INDIA will be inserted. Similarly, if the
user does not specify the value for the DOJ column, then the default current
date value will be inserted.
INSERT INTO Employee (ID, Name, Age) values(1, 'Anurag', 30);
Add Default constraint using ALTER TABLE

ALTER TABLE Persons


MODIFY City DEFAULT 'PUNE';
6. What is a foreign key in Oracle?
When a primary key from one table appears in another table, it is called a foreign
key.

A foreign key is a way to enforce referential integrity within your Oracle database.
A foreign key means that values in one table must also appear in another table.

The referenced table is called the parent table while the table with the foreign
key is called the child table. The foreign key in the child table will generally
reference a primary key in the parent table.

A foreign key can be defined in either a CREATE TABLE statement or an ALTER


TABLE statement.
Referential integrity

• A REFERENTIAL INTEGRITY is a database concept that is used to build and maintain logical
relationships between tables to avoid logical corruption of data. It is a very useful and
important part in DBMS.
• Usually, referential integrity is made up of the combination of a primary key and a foreign key.
• The main concept of REFERENTIAL INTEGRITY is that it does not allow to add any record in a
table that contains the foreign key unless the reference table containing a
corresponding primary key.
• If any record in referenced table (i.e. the table who contain primary key) is deleted, all the
corresponding records in the referencing table will be deleted for the referential integrity.

Referential integrity is a term used in database design to describe the relationship between two
tables. It is important because it ensures that all data in a database remains consistent and up
to date. It helps to prevent incorrect records from being added, deleted, or modified.
Referential integrity is a constraint on the database design that makes certain that each foreign
key in a table point to a unique primary key value in another table.
• At Column level
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype REFERENCES parent_table (column));

Example
Create table emp( empid number(3) primary key,empname varchar(15),
birthdate date);

create table department(did number(3) primary key, dname


varchar2(25),empid number(3) REFERENCES emp(empid));
Eg :
create table e1
(
empid number(3) primary key,
ename varchar2(20) not null
)
create table d3(did number(3) primary key, dname varchar2(25),empid number(3) REFERENCES
e1(empid));

insert into e1 values(1,'Ram')


insert into e1 values(2,'Tam')
insert into e1 values(3,'Sam')

select * from e1

insert into d3 values(21,'HR',1)


insert into d3 values(22,'Account',2)
IF you will try to insert

insert into d3 values(23,'Account',5)

It will give you error

ORA-02291: integrity constraint (SYSTEM.SYS_C004001) violated - parent key not found.


At table level
Using a CREATE TABLE statement
Syntax
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...

CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
);
CREATE TABLE e2 ( empid NUMBER PRIMARY KEY, ename VARCHAR2(100) NOT
NULL );
CREATE TABLE d2 ( did NUMBER PRIMARY KEY, dname VARCHAR2(100) NOT NULL,
empid NUMBER, CONSTRAINT fk_empid FOREIGN KEY (empid) REFERENCES
e2(empid) );

INSERT INTO e2 VALUES (1, 'John');


INSERT INTO e2 VALUES (2, 'Alice');
INSERT INTO e2 VALUES (3, 'Bob');

INSERT INTO d2 VALUES (10, 'HR', 1);


INSERT INTO d2 VALUES (20, 'IT', 2);
INSERT INTO d2 VALUES (30, 'Finance', 3);
Using an ALTER TABLE statement
Syntax
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n);
Example
ALTER TABLE products
ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id);
Drop a Foreign Key
Once a foreign key has been created, you may find that you wish to
drop the foreign key from the table. You can do this with the ALTER
TABLE statement in Oracle.

Syntax:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example:
ALTER TABLE products
DROP CONSTRAINT fk_supplier;

You might also like