[go: up one dir, main page]

Dma Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 69

Database Management

Chapter 1: Creating Relational Database


1.1 .Relational database design
 RDBMS uses a collection of tables to represent both data and relationship among those data.
 Each table has multiple rows and multiple columns; each column has a unique name.
 Rows of table correspond to Tuples of the table.
 Columns of table correspond to attributes of the table.
Cus_id Cus_name Cus_city Acc_no Balance
1 Anil Pune 101 1000
2 Sunil Mumbai 102 2000
3 Yash Delhi 103 3000
4 Raj Pune 104 4000

Fig. Customer table Fig. Account Table


Cus_id Acc_no
1 101
2 102
2 103
3 104
4 104
Fig. Depositor Table
Fig. Sample Relational Database
 Fig.shows sample relational database consist of three tables
 The first table customer shows customer of bank. For e.g. customer identified by cus-id 1 is named
Anil and lives in pune city.
 The second table account shows accounts of customer. For e.g. account with acc_no 101 has
balance of 1000 rupees.
 The third table depositor shows which account belongs to which customer
For e.g. The customer whose cus_id 2 has two accounts:102 with balance of 2000 rupees and 103
with balance of 3000 rupees.
What is DBMS?
 DBMS=Database+Management system
 Database is collection of data and management system is a set of programs to access and
manipulate those those data.

What is RDBMS?
 RDBMS stands for relational database management system.
 RDBMS is a software system which is used to store large amount of data in the form of multiple
tables and to perform different operations on those data. or
 RDBMS is a collection of interrelated data and set of programs to access and manipulated those
data. In addition to this data in RDBMS is stored in the form of multiple tables.
 Each table in RDBMS has multiple rows and multiple columns.
 Rows of table correspond to records of table and columns of table correspond to attributes of table.
 RDBMS allows us to insert, update, delete, and retrieve data from relational database.
 Most poplar RDBMS software’s are Oracle, Microsoft SQL server, IBM DB2, MySQL, Sybase and
So on.

1
Database Management

Different types of RDBMS software:


 There are number of different database software’s are available for storing and managing data in a
database.
 All database products support SQL.
 SQL(Structured Query Language) is a standard language for storing, retrieving and manipulating
data in a database

Different RDBMS Software’s are:


1. Oracle-
- It’s a RDBMS software developed and marketed by Oracle Corporation.
- Oracle supports SQL and PL/SQL.
- Oracle is a first software support the SQL and now SQL becomes an industry standard for database
products.
-Oracle database runs on major platforms including windows, Linux, Unix and MacOS.
-Oracle is suitable for large database applications.
2. My SQL-
-It’s most popular open-source RDBMS software product used for developing web based applications.
-MySQL is developed and marketed by Swedish company MySQL AB, which is now owned by Oracle.
- MySQL supports SQL but not supports PL/SQL.
-MySQL is supporting many different platforms including Microsoft Windows, Linux, UNIX, and
Mac OS.
3. Microsoft SQL server-
-It’s RDBMS software developed by Microsoft
-It’s database server product with primary function is to store and retrieve data as requested by other
applications which may either run on same computer or on another computer across the network
4. IBM DB2-
- It’s database server product developed by IBM.
-DB2 is designed to store, analyze and retrieve data efficiently
-DB2 product is extended with support of object oriented features.
- DB2 server runs on major platforms including windows, Linux, Unix and MacOS.
5. Sybase DB-
- Sybase DB is a relational database server product for businesses developed by Sybase Corporation
- Sybase DB used on the Unix platform, but is also available for Microsoft Windows platform.
- Sybase is an enterprise software and services company that produced software to manage and analyze
information in relational databases. Sybase was acquired by SAP in 2010
6. Ingress-
- Ingres Database is a commercially supported, open-source SQL relational database management
system intended to support large commercial and government applications. Ingres Database is fully open
source with a global community of contributors

2
Database Management

1.2 Relational Terminology


Attributes

Primary key Cus_id Cus_name Cus_city


Domain of cus_id attributes 1 Sunil Pune
2 Yash Mumbai Tuple
3 Raj Delhi
Fig. Customer table
 Relation:-It’s a simple table, each table has multiple rows and multiple columns; each column has
a unique name.
Properties of relation
1. Each relation has unique name with in database
2. Relation consist only one type of information
3. Each relation has fixed number of columns and each column has unique name
4. Rows and columns are unordered
5. There are no duplicate tuples
 Attributes:- attributes are columns in a table.
Consider a customer table, it has three columns namely, cus-id, cus-name, cus-city. These table
columns are called attributes.
 Tuples:-Tuples are rows in a table.
 Domain:-set of possible values of particular attribute are called domain of that attribute.
 Degree of relation:-It’s the number of columns in relation
 Cardinality of relation:- It’s the number of rows in relation
 Primary key:-It’s attribute used to uniquely identify tuples in a relation

Relational Algebra
 Relational algebra consists of set of operations that takes one or two relations as input and produce
new relation as a output.
Relational algebra consist of two types of operations :
1. Unary operations : Operates on one relation
2. Binary operations : operates on two relations
Relational algebra operations

Unary Operations Binary Operations

Select (σ) Sigma Union (U)

Project (π) pi Set difference (-)

Rename (ρ) rho Cartesian product (x)

Set intersection (n)

Natural join ( )
Fig. Relational Algebra operations

3
Database Management

1. Select Operation (σ) :


 Select operation selects those tuples that satisfy a given condition.
 For giving condition we use =, ≠, <, ≤, >, ≥ comparison operators in select operation.
 Select operation denoted by lowercase Greek latter sigma (σ).
 For combining different conditions into single one we use logical operators like And (^), OR(v),
NOT (˥)
Loan_no Branch_name Amount
L-10 Pune 1000
L-11 Mumbai 2000
L-12 Nashik 3000
L-13 Pune 4000
L-14 Delhi 5000
Fig. Loan relation

For example :
1. Select those tuples of loan relation where the branch is pune

σbranch_name = “pune” (loan)

2. Find tuples of loan relation whose amount is greater than 3000.

σAmount > 3000 (loan)

3. Find those tuples of loan relation whose loan amount is greater than 3000 and whose branch is
Pune.

σamount > 3000 ^ branch-name = “Pune”(loan)

2. Project Operation (π) :


 Project operation display the selected attributes from relation.
 Project operation denoted by uppercase Greek letter pi (π)
For example :
1. Display all loan number and loan amounts from loan relation.

π loan_no, amount (loan)

Combination of Select and Project operation :


 If we want to find only those records who satisfy specific condition then we need to use
combination of select and project operation
For example :
1. Find these customer names who live in pune city

π cus_name (σcus_city = “Pune” (customer))


2. Find only those loan numbers whose loan amount is greater than 4000

π loan_no (σamount > 4000 (loan))

4
Database Management

3. Rename Operation (ρ) :


 Unlike relations, the results of relational algebra expressions don’t have a name, so we can give
names to them with rename operation.
 Rename operation is denoted by lowercase Greek letter rho (ρ).
 Given relational algebra expression E, the expression x  E  returns result of expression E under
name x.
 Assume that the relational algebra expression E has n attributes then the expression

x  A1 , A2 , A3 ........An  E 

Returns result of expression E under name x and attributes renamed with A, A2, A3, …….. An.
 For Example : Find customer names who live in Pune city and give name employee to result and
give column name as a emp_name instead of cus_name.

 employee(emp_name) (πcus_name (σcus_city=”Pune” (customer))

4. Union Operation (U) :


 Union operation is a binary operation.
 It operates on more than one relation.
 Union operation combines tuples from two relations and form third relation.
 It does not contain duplicate values
 Union operation denoted by U symbol
Cus_name Acc_no Cus_name Acc_no
Sunil A-101 Sunil L-10
Yash A-102 Yash L-11
Raj A-103 Manish L-12
Fig. Depositor relation Fig. borrower relation
 For eg. 1 : Find the names of all customers who have either an account in bank or who have taken
loan from bank or both.

Πcus_name (depositor) U πcus_name (customer)

Result :
Cus_name
Sunil
Yash
Raj
Manish names who have either account or loan or both.
Fig. : Customer

5. Set-intersection operation (∩) :


 It’s a binary operation, operators on two relations.
 It displays common values from two tables.
 Its denoted by ∩ symbol.
 It does not contain duplicate value.

5
Database Management

 For e.g. 1 : Find the customer names who have both account and loan at the bank.

πcus_name (depositor) ∩πcus_name (borrower)

Result :
Cus-name
Sunil
Yash
Fig. : Customer names with both account and loan at bank.
6. Set difference(-) :
 It’s a binary operation, operates on two relations.
 Its used to find those tuples that are in one relation but not in another relation.
 Its denoted by –(minus) symbol.
 It does not contains duplicate values.
 For e.g. (1) : Find all customers who have account at the bank but who have not taken loan from
bank.
πcus_name (depositor) – πcus_name (borrower)

Result
Cus-name
Raj

7. Cartesian-product operation (X) :


 It’s a binary operation operates on two relations.
 Cartesian product is the operation where one relation would be multiplied by other relation.
 Its denoted by a cross (X) symbol.
 Cartesian product of relation r1 and r2 written as r1  r2 .

Cus_name Acc_no. Loan_no Branch_name Amount


Sunil L-10 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Sachin L-12 L-12 Pune 2000
Fig. Borrower relation Fig. Loan relation
Cus_name
Borrower.loan_no Loan.Loan_no Branch_name Amount
Sunil L-10 L-10 Pune 500
Sunil L-10 L-11 Mumbai 1000
Sunil L-10 L-12 Pune 2000
Yash L-11 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Yash L-11 L-12 Pune 2000
Sachin L-12 L-10 Pune 500
Sachin L-12 L-11 Mumbai 1000
Sachin L-12 L-12 Pune 2000
Fig. Borrower x loan

6
Database Management

 For e.g. (1) : Find names of all customers who have loan at the bank and also find their respective
loan amount.
Πcus_name, amount (σborrower.loan_no.=loan.lon_no (borrower x loan))

 For e.g. (2) : Find names of customers who have taken loan from Pune branch.
Πcus_name (σbranch_name=”pune” (σborrower.loan_no.=loan.lon_no (borrower x loan)))

8. Natural Join Operation ( ):


 It’s a binary operation, operates on two relations.
 It combines certain selection and Cartesian product operations into single operation.
i.e. It combines select and Cartesian product operation into single operation.
 Its denoted by join symbol .
Cus_name Loan_no Loan_no Branch_name Amount
Sunil L-10 L-10 Pune 500
Yash L-11 L-11 Mumbai 1000
Sachin L-12 L-13 Pune 2000
Fig. Borrower table Fig. Loan relation
Loan_no Cus_name Branch_name Amount
L-10 Sunil Pune 500
L-11 Yash Mumbai 1000
Fig. Borrower loan
 For e.g. (1) : Find names of all customers who have loan at the bank and also find their respective
loan amount.
cus_name, amount (borrower loan)

 For e.g. (2) : Find names of customers who have taken loan from Pune branch.

Πcus_name (σbranch_name=”pune” (borrower loan))

Solved Examples:
Example: 1. Consider the structure as
product_master = {prod_id, prod_name, rate}
purchase_details = {prod-id, quantity, dept_no., purchase_rate}
Write relational algebra expression for following:
1. Get product_id, prod_name and quantity for all purchased products.
2. Get the products with rates between 100 and 4500.
Answer: 1. πprod_id, prod_name, quantity (product_master purchase_details)
2. πprod_id, prod_name (σrate > = 100 ^ rate < = 4500 (product_master)

Example :2. Consider following relational database patient_details (patien_id, patient_name,


prescription, doctor) give an expression in relational algebra for following queries:
(1)To get prescription given to Sanjay.
(2)To get patient_id with their name.
Answer : (1) πprescription(σpatient_name = “Sanjay” (patient_details))
(2) πpatient_id, patient_name (patient_details)

7
Database Management

Example :3.Consider the structure as :


Customer (cust.id, cust.name, cust.add, cust.city, account.no)
Write relational algebra expression for following
(1) Find information of only those customers who live in city Pune.
(2) Find cust.id, cust.name from the customer database.
Answer :(1) σcust.city = “pune” (customer)
(2) πcust.id, cust.name (customer)

1.2 Introduction to SQL:


 SQL(Structured Query Language) is a standard language for storing, retrieving and manipulating
data in a database
 The SQL is divided into different parts as below:
Data Definition Language (DDL): DDL is used to create or modify structure of table and to apply
some integrity constraints on a table.
Data Manipulation Language (DML): DML is used to access or manipulate( i.e. add, modify or
delete) data from table.
Data control Language (DCL): DCL is used to control access to data from database.
DCL provides security to the database.
Transaction Control Language (TCL): TCL is used to manage transactions in the database.

Data Types in SQL :


1. Char (n) :
This data type is used to store characters, symbols and numbers.
This data type stores fixed length character string.
The maximum data stored by this data type is 2000 characters
e.g name char(10)
If user enters 3 character names then 10 bytes are allocated to store name.

2. Varchar2 (n):
This data type is used to store characters, symbols and numbers.
This data type stores variable length character string.
The maximum data stored by this data type is 4000 characters
e.g name varchar2(10)
If user enters 3 character names then only 3 bytes are allocated to store name not 10 bytes
Varchar2 data type saves memory space as compared with char data type.

3. Number (p,s) :
This data type is used to store fixed or floating point numbers. P is the precision (i.e. total no. of
digits with in number) and S specifies scale (i.e no. of digits after decimal point). The maximum
precisions are 38 digits.
e.g. Percentage number (5, 2)
4. Long:
This data type is used to store the variable length character string containing data up to 2 GB.
The long data type can be assigned to only one column in a table.
e.g doc long

5. Date:
This data type is used to store date and time in a table.
The standard format used to store the date is DD-MON-YY
e.g. dob date.

8
Database Management

DDL (Data Defination Language) Commands :


 DDL commands are used to create or modify structure of table and to apply some integrity
constraints on a table.
DDL commands are:
1. Create table-It is used to create structure of table or to apply some integrity constraints on table
Syntax: Create table table_name
(column_name1 datatype(size) primary key,
column_name2 datatype(size) not null,
. .
. .
column_namen datatype(size));

Example: To create table for schema student(rollno,name,class)


Create table student
( rollno number(5) primary key,
name char(10) not null,
class char(10));

2. Desc(describe table): : Its is used to display structure of table.


Syntax: desc table_name;

Example:To display structure of student table


desc student;

3. Alter table: It is used to modify the structure of table.


With alter table command we can:
 add new column to existing table or
 to modify the data type or size of particular column or
 to drop any particular column from the table. or
 to change name of column from particular table
Syntax 1:for add option:
alter table table_name
add ( column_name1 datatype(size),
column_name2 datatype(size),
. .
. .
column_namen datatype(size));

Example:1 To add new column percentage to student table


alter table student
add (percentage number(5,2));
Syntax 2:for modify option:
alter table table_name
modify (column_name1 datatype(size),
column_name2 datatype(size),
. .
. .
column_namen datatype(size));

Example:2 To modify data type of name column to varchar2 from student table
alter table student
modify (name varchar2(20));

9
Database Management

Syntax 3:for drop option:


alter table table _name
drop column column_name;
Example:3 To drop class column from student table
alter table student
drop column class;

Syntax 4:for rename option:


alter table table _name
rename column old_column_name to new_column_name;
Example:4 To rename column name to student_name from student table
alter table student
rename column name to student_name;

4. Truncate table: It is used to remove all rows from table but it keeps structure of table as it is in a
database.
.
Syntax: Truncate table table_name;
Example: To remove all data from from student table
Truncate table student;

5. Drop table: It is used to remove all rows from table and structure of table from database.

Syntax: drop table table_name;


Example: To remove table student from database
drop table student;

6. Rename: It is used change the name of table.

Syntax: rename old_table_name to new_table_name;


Example: To change name of table student to stud_info;
rename student to stud_info;

7. Create user:It is used to create new user in a database.

Syntax: create user username identified by password;


Example: To create user abc having password abc123
create user abc identified by abc123;

Difference between drop table and truncate table command


DROP TRUNCATE
1. It is used to remove all rows from table and It is used to remove all rows from table but it
structure of table from database. keeps structure of table as it is in a database
2. It deletes entire table at once from disk 2. It deletes all records from table at once
3. Column Structure of table does not remain on 3. Empty column structure of the table remains on
the disk. the disk.
4.Syntax : Drop table table_name; 4. Syntax : Truncate table table_name;
5. Example : Drop table student; 5. Example : Truncate table student;

10
Database Management

Use of Data Constraints:


 Integrity constraints means data value stored in database must satisfy certain conditions.
 Integrity constraints are used to avoid invalid data entry into a table.
 Integrity constraints are used to maintain correctness and accuracy of data stored in database.

Examples of integrity constraints:


1. An account balance can’t be NULL.
2. No two account can have same account number.
3. In bank account balance can’t be less than 500 Rupees.
Integrity constraints

Domain Integrity Entity Integrity Referential Integrity constraint


Constraint Constraint or foreign key constraint

NOT NULL Check Primary Key Unique


Constraints Constraint Constraint Constraint

Fig. : Types of Integrity Constraints

1. Domain Integrity Constraints:


 It’s used to maintained value according to user specification or requirements.
 There are two types of domain integrity constraints
a) NOT NULL constraint
b)Check constraint

a) NOT NULL Constraint:


 By default all columns in a table allow null values when a ‘NOT NULL’ constraint is apply on a
column then column will not allow null values.
 Not NULL constraints can be specified at the time of table certain with create table command or
can be specified after table creation with alter table command

 e.g Create table student


(roll_no number(5),
name char(10) not null);

b) Check constraint:
 The check constraint defines a condition on column and column values must satisfy defined
condition.
 The check constraint can be specified at the time of table creation with create table command or can
be specified after table creation with Alter table command

 e.g. Create table student


(roll_no number(5),
name char(10) ,
percentage number(5,2) check (percentage>=40));
11
Database Management

2. Entity Integrity Constraint:


 It’s used to assure that every relation has a primary key and values of primary key should be unique
and not null.
 There are two types of Entity Integrity constraints
a) Primary key constraint
b) Unique constraint
a) Primary Key Constraint:
The primary key constraint maintains unique and not null values for primary key column in a table.
 e.g. Create table student
(roll_no number(5) primary key,
name char(10) ,

b) Unique Constraint :
The unique constraint maintains unique values in a particular column of a table but it allows null
values
 e.g. Create table account
(roll_no number(5),
name char(10) ,
mobile_no number(10) unique);

3. Referential Integrity Constraint:


 Referential integrity means the values that are present for primary key column in a parent table
same values must present for foreign key column in a child table.
 Referential integrity constraint maintains a parent child relationship between two tables.
 Referential integrity maintained using foreign key.
 A foreign key is attribute in one table that refers values of primary key column of another table.
 For example
Primary Key Primary Key Foreign Key

Branch_name Branch_city Assets Acc_no Branch_name Balance


1000000 101 Vashi 1000
Vashi Navi Mumbai
2000000 102 Nerul 2000
Nerul Navi Mumbai
Fig. Branch Table(Parent Table) Fig. Account Table (Child Table)

Create table Branch


(Branch_name char (20) primary key,
Branch_city char (20),
Assets number (10)),

Create table Account


(Acc_no number (10) primary key,
Branch_name char (20),
Balance number (8, 2),
Foreign key (Branch_name) references Branch(Branch_name));

Fig. Foreign key declaration using SQL DLL

12
Database Management

On delete cascade constraint:


On delete cascade constraint tells RDBMS that when row in parent table is deleted the dependent rows in
child table will also automatically get deleted.
 For example
Primary Key Primary Key Foreign Key

Branch_name Branch_city Assets Acc_no Branch_name Balance


1000000 101 Vashi 1000
Vashi Navi Mumbai
2000000 102 Nerul 2000
Nerul Navi Mumbai
Fig. Branch Table(Parent Table) Fig. Account Table (Child Table)

Create table Branch


(Branch_name char (20) primary key,
Branch_city char (20),
Assets number (10)),

Create table Account


(Acc_no number (10) primary key,
Branch_name char (20),
Balance number (8, 2),
Foreign key (Branch_name) references Branch(Branch_name) on delete cascade) ;

Fig. On delete cascade constraint declaration using SQL DLL

In above example when rows of any branch from branch relation is deleted then dependent rows of same
branch from account relation will be automatically gets deleted.

13
Database Management

Chapter. 2 – Interactive SQL for data extraction


2.1 DML (Data Manipulation Language) Commands:
 DML commands are used to access or manipulate data from database.
 The type of manipulates are-
1. Insertion of new information into database
2. Modification of information stored in database
3. Deletion of information stored in database
4. Retrieval of information stored in database
DML commands are:
1. Insert – it’s used to insert new row into table.

Syntax 1: insert command without defining columns


Insert into table_name
values (value1,value2,…..);
Example 1: insert into student
values(1,’raj’,60);

Syntax2: insert command with defining columns


Insert into table_name (column_name1, column_name2,.…)
values (value1,value2,…..);
Example 2: insert into student (name,rollno,percentage)
values (’rajesh’2,,70);

Syntax3: insert values for specific columns in a table.


Insert into table_name (column_name1, column_name2)
values (value1,value2);
Example 3: insert into student (rollno,name)
values(3,’ram’);

Syntax4: insert values into table by accepting values from user.


Insert into table_name
values (&column_name1, &column_name2,.…)
Example 4: insert into student
values (&rollno,’&name’,&percentage);
Syntax 5: insert values into table by accepting values from existing table.
Insert into table_name
Select * from existing_table_name
Example 5 : insert into student
Select * from studinfo;_____
2 Update: It is used to modify the existing data from table
Syntax1: update table_name
set column name=new value
where condition;
Example 1 : Change name of student raj to rajesh
update student
set name=’rajesh’
where name=’raj’;

Example 2 : Increase percentage of all student with 10 %


update student
set percentage=percentage+percentage*10/100;

14
Database Management

3. Delete: It is used to remove all or specific rows from table


Syntax 1 : To remove all rows from table
delete from table_name

Example 1 : To remove all rows from student table


delete from student

Syntax 2: To remove specific rows from table


delete from table_name
where condition
Example 2: To remove students whose percentage is less than 50
delete from student
where percentage <50

4. Select: select command is used to display(retrieve) all or specific column from table

Syntax 1: To display all columns by satisfying given condition


select * from table_name
where condition;
Example 1: To display details of student whose percentage is greater than 60
select * from student
where percentage >60;

Syntax 2: To display specific columns by satisfying given condition


select column_name1, column_name2, ….
from table_name
where condition;
Example 2: To display rollno and names of student whose percentage is greater than 60
select rollno,name
from student
where percentage >60;

15
Database Management

SQL Operators:
The SQL provides following operators:
1. Arithmetic operators
2. Comparison operators(Relational operators)
3. Logical operators
4. Set operators
5. Range searching operators
6. Pattern matching operators
1. Arithmetic Operators:
 Arithmetic operators are used to perform arithmetic operations.
 There are four arithmetic operators.
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
Operator Meaning
+ Adds values or operand on either side of operator
- Subtract right side operand from left side operand
* Multiplies left side operand with right side operand
/ Divides left side operand by right side operand

Example 1. Display salary of all employees by adding 5000 to it


Select sal + 5000 from emp;
Example 2. Display salary of all employees by increasing salary with 5%
Select sal + ( sal * 5/100 ) from emp;

2. Comparison Operators (Relational operators) :


 Comparison operators are used to compare two operands or to compare expressions.
 The SQL uses comparison operators such as: =, != , >,>=, <, <=, !>, !<

Operator Meaning
Checks if value of two operands are equal or not ,if equal then
=
condition becomes true
Checks if value of two operands are equal or not ,if not equal then
!=
condition becomes true
Checks if value of left operand is greater than value of right operand, if
>
yes then condition becomes true
Checks if value of left operand is greater than equal to value of right
>=
operand, if yes then condition becomes true
Checks if value of left operand is less than value of right operand, if
<
yes then condition becomes true
Checks if value of left operand is less than equal to value of right
<=
operand, if yes then condition becomes true

Example 1. Display details of employees whose job is clerk


Select * from emp where job=’clerk’;
Example 2. Display details of employees except job as clerk
Select * from emp where job !=’clerk’;
Example 3. Display details of employees whose salary is greater than 20,000
Select * from emp where sal > 20000;

16
Database Management

3. Logical Operators:
 Logical operators are used to combine multiple conditions in where clause.
 The SQL uses logical operators such as : AND, OR, NOT
Operator Meaning
AND Returns result when all conditions are true
OR Returns result when any one condition is true
NOT Returns result except specified condition

Example 1. Display details of employees whose job is clerk and whose deptno is 10
Select * from emp where job=’clerk’ and deptno=10;
Example 2. Display details of employees whose job is clerk or salesman
Select * from emp where job =’clerk’ or job =’salesman’;
Example 3. Display details of employees whose job other than clerk
Select * from emp where not job=’clerk’;

4. Set Operators:
 The set operators operates on two relations
 The set operators are used to combines the result of two queries into a single result
 The SQL provides following set operators:
1. Union
2. Intersect
3. Minus
Syntax: SQL statement1 set operator SQL statement2;

1. Union: it is used to display all values from both tables.


Example: Display employee names who works in India or USA
Select ename from emp_india
union
Select ename from emp_usa ;

2. Intersect: it is used to display common values from both tables.


Example: Display employee names who works in both India and USA
Select ename from emp_india
intersect
Select ename from emp_usa ;

3. Minus: it is used to display values that are present in one table but not present in other table.
Example: Display employee names who works in India but not in USA
Select ename from emp_india
Minus
Select ename from emp_usa ;

5. Range searching operators-


 Range searching operators are used to find the values that are within specific range
 SQL provides following range searching operators:
1. Between
2. Not between
3. In
4. Not In
1. Between: It finds the values that are within specific range
Syntax: select * from table_name
where column_name between value1 and value2;
Example: find employees details whose salary between 10000and 20000
Select * from emp where sal between 10000 and 20000;
17
Database Management

2. Not between: It finds the values that are not within specific range
Syntax: select * from table_name
where column_name not between value1 and value2;
Example:find employees details whose salary not between 10000and 20000
Select * from emp where sal not between 10000 and 20000;

3. In: It finds the values that are matches with any one value in a list
Syntax: select * from table_name
where column_name In (value1,value2,value3,……..);
Example:find employees details whose job is clerk, salesman or manager
Select * from emp where job in (‘clerk’,’salesman’,’manager’);

4. Not In: It finds the values that are not with matches any value in a list
Syntax: select * from table_name
where column_name Not in (value1,value2,value3,……..);
Example:find employees details whose job is other than clerk, salesman or manager
Select * from emp where job Not in (‘clerk’,’salesman’,’manager’);

6. Patterns matching operators-


 Patterns matching operators are used to retrieve data from table with particular pattern
 SQL provides following patterns matching operators:
1. Like
2. Not like
3. is null
4. is not null
1. Like: It displays all rows from table where data matches with specified pattern
We describe pattern by two special characters
%( Percent): it represents string of zero or more characters
_ (Underscore): it represents single characters

Syntax: select * from table_name


where column_name like ‘pattern’;
Example 1: find employees details whose name starts with ‘ra’
select * from emp where ename like ‘ra%’;
Example 2: find employees details whose name ends with ‘sh’ and name contains maximum of 6
characters
select * from emp where ename like ‘_ _ _ _sh’;

2. Not like: It displays all rows from table where data does not matches with specified pattern
Syntax: select * from table_name
where column_name not like ‘pattern’;
Example: find employees details whose name does not contain pattern ‘ra’
select * from emp where ename not like ‘%ra%’;

3. is null: The null values can be retrieved from table using is null keyword in where clause
Syntax: select * from table_name
where column_name is null;
Example: find employees details who do not get commission.
select * from emp where comm is null;

4. is not null: The not null values can be retrieved from table using is not null keyword in where clause
Syntax: select * from table_name
where column_name is not null;
Example: find employees details who does gets some commission.
select * from emp where comm is null;

18
Database Management

2.2 In built Functions:


 Function is ready to use code written and tested by expert. User just needs to know how to use it by
passing the required value and get the required answer.it may have one or more argument and may
return a value.
 SQL provides following functions:
1. String functions or Character functions
2. Arithmetic or Numeric functions
3. Date functions
4. Data conversion functions
5. Aggregate functions

1. String functions :
 String functions accept string values or character values as input and returns string values as
output.
 Only one function length returns the numerical value as output.
SQL provides following string functions:

Sr. No Function Description

Converts first letter of string to capital letter.


Initcap(str) Example:
1. Select initcap(ename) from emp;
Converts a string to all lowercase characters.
Lower(char) Example:
2. Select lower(ename) from emp;
Converts a string to all uppercase characters.
Upper(char) Example:
3. Select upper(ename) from emp;
It returns length of character string.
Length(char) Example:
4. Select length(ename) from emp;

It trim from the left of character string.


Ltrim(char,set) Example:
5.
Select Ltrim(‘hello hi’,’hello’) from dual;
It trim from the Right of character string.
Rtrim(char,set) Example:
6. Select Ltrim(‘hello hi’,’hi’) from dual;

Concat(string1,string2) It merge or combines two string into single string


7. Example:
Select Concat(‘hello’ ,’ram’) from dual; or
Select ‘hello ’ ||’ram’ from dual

It returns substring of character string starts from mth character


Substr(char,m,n) and is of length n characters
8. Example:
Select Substr(‘Triangle’,4,5) from dual;

19
Database Management

2.Arithmetic or Numeric Functions:


 Numeric functions accept the numeric value as the input and returns the numeric value as output.
SQL provides following numeric functions:
Name Description
It returns the absolute value of the number.
Abs(n)
e.g. Select abs(-2.5) from dual;
It returns m raised to the nth power
Power (m,n)
e.g select power(2,3) from dual;
It returns the remainder of m divided by n.
Mod(m,n)
e.g select mod(11,3) from dual;
It returns square root of the number.
Sqrt(n)
e.g. Select sqrt(25) from dual;
It returns e raised to the nth power, where E = 2.71828183....
Exp(n)
e.g. Select exp(14.3) from dual;
It returns the smallest integer greater than or equal to n
Ceil(n)
e.g. Select ceil(14.3) from dual;
It returns the largest integer equal to or less than n
Floor(n)
e.g. Select floor(14.3) from dual;
It returns m rounded to m decimal places
Round(m, [n])
e.g. Select round(54.56,1) from dual;
It returns m truncated to n decimal places.
Trunc(m, [n]) e.g. Select trunc(54.56,1) from dual;

It returns greatest of list of expressions


Greatest (expr1,expr2,…)
e.g. Select greatest(3*2,8/2,5) from dual;
It returns least of list of expressions
Least (expr1, expr2,….)
e.g. Select least(3*2,8/2,5) from dual;

3. Date and Time functions:


 Date functions operate on oracle dates.
 Date functions deals with date datatype column of table
 Date functions generally returns date datatype value
 Only one function months_between returns the numerical value.
 SQL provides following date functions :
Name Description
It returns number of months between two dates.
Months_between(date1,date2) Example:
Select months_between(’05-may-2016’, ’05-jan-2016’) from dual
It returns date after adding number of months to date
Add_months (date, no. of months)
Example:
Select add_months(’05-may-2016’, 3) from dual
It returns date of given week day after specified date
Next_day(date,day of week) Example:
Select next_day (’05-may-2016’, ‘monday’) from dual
It returns the last day in the month of the specified date.
Last_day(date) Example:
Select last_day (’05-may-2016’) from dual
It returns the date rounded by the specified format unit.
format may be year, month or day
Round(date,format)
Example:
Select round (sysdate,’year’ ) from dual
Trunc(date,format) It returns the date with time portion of date truncated to the unit

20
Database Management

specified in format.
format may be year, month or day
Example:
Select trunc(sysdate, ’year’ ) from dual
It returns systems current date and time
Sysdate Example:
Select sysdate from dual

4. Data conversion Functions:


 Conversion functions convert the values of one data type to another data type.
 SQL provides following data conversion functions :
1. To_char( )
2. To_date ( )
3. To_number( )
1. To_char( ) : It converts date or number value into a character string

Syntax: select to_char(expr,format)


Example 1:To display system date in format June 4,2018
select to_char (sysdate,’Month DD, YYYY’) from dual;

Example 2: To display salary of employee in format $99,999


select to_char(sal,’$99,999’) from emp;

2. To_date( ) : It converts number or character string into date format

Syntax: select to_date(expr,format)


Example 1:To display string ‘January 01 2016’ into date format
select to_date(‘January 01 2016’,’DD-MON-YYYY’) from dual;

3. To_number : It converts character string containing a number into a number data type.

Syntax: select to_number(char)


Example 1: To display salary in number format
select to_number (sal) from emp;

Special Date formats using To_char( ) function:

Example 1:To display system date in DD/MM/YYYY format


select to_char (sysdate,’DD/MM/YYYY’) from dual;

Example 2:To display system date in format ‘6th of june 2018


select to_char(sysdate,’dd”th of” Month yyyy’) from dual;

Example 3:To display system date in DD-MON-YY HH:MI:SS format


select to_char(sysdate,’DD-MON-YY HH:MI:SS’) from dual;

Example 4:To display system date in AM/PM format


select to_char(sysdate,’DD-MON-YY AM’) from dual;

Example 5:To display system date in format Monday,August 13,2018


select to_char(sysdate,’day,month dd,yyyy’) from dual;

21
Database Management

5. Aggregate functions:
 Aggregate functions are functions that takes set of values as input and return single value as
output.
Syntax: Select aggregate function (column_name) from table_name
where condition;
SQL provides following aggregate functions:
1. Min: It returns the smallest value in a given column
Example: Find minimum salary of employee
select min (sal) from emp;
2. Max: It returns the largest value in a given column
Example: Find maximum salary of employee
select max (sal) from emp;
3. Sum: It returns the sum of the values in a given column
Example: Find total salary of employee
select sum (sal) from emp;
4. Avg: It returns the average value of a given column
Example: Find average salary of employee
select avg (sal) from emp;
5. Count: It returns the total number of values in a given column
Example: Find total no. of employees in emp table
select count (empno) from emp;
6. Count (*) : It returns the number of rows in a table
Example: Find no. of rows in emp table
select count (*) from emp;
7. Distinct : It returns distinct(unique) values in a given column
Example: Find unique salary values in emp table
select distinct(sal) from emp;

22
Database Management

2.3 Queries using Group by, having and order by clause:


Group by clause:
 It’s used to group the rows based on certain common criteria.so that aggregate functions may be
performed on group with one command. or
 Group by clause used to divide the rows in a table into groups and apply aggregate function on
that group.
Syntax: select column_name, aggregate_function(column_name) from table_name
where condition
group by column_name;

Example 1: display maximum salary of each department


select deptno, max(sal)
from emp
group by deptno;
Example 2: display maximum salary of each job type
select job, max(sal)
from emp
group by job;

Having clause:
 Having clause is used to give condition after group by clause or
 Having clause is used is used to specify which groups are to be displayed.
Syntax: select column_name, aggregate_function(column_name)
from table_name
where condition
group by column_name
having condition;

Example 1: display department numbers having maximum salary greater than 40000
select deptno, max(sal) from emp
group by deptno
having max(sal)>40000;

Example 2: display department numbers having no.of employees greater than 2


select deptno, count(empno) from emp
group by deptno
having count(empno) > 2 ;

Order by clause
 Order by clause is used to display records from table in ascending or descending order of specific
column. By default the order is ascending.
Syntax: Select * from table name
where condition
order by column_name [asc/desc];
Example 1: display details of employee in ascending order of salary
Select * from emp
order by sal asc;
Example 2: display details of employee in descending order of salary
Select * from emp
order by sal desc;

23
Database Management

2.4 Joins :
 Joins are used to retrieve the data from multiple tables one the basis of common attribute.
 Joins are used to combine data from multiple tables
Types of Joins are as follows:

1) EQUI JOIN:
 A join which is based on equalities is called equi join.
 In equi join comparison operator “=” is used to perform a Join.
Syntax: select table1.column_name1, table1.column_name2,…………..
from table1,table2
where table1.column_name=table 2.column_name;
Example: display employee names and their respective department name
Select emp.ename,dept.dname
From emp,dept
Where emp.deptno=dept.deptno;

2) NON-EQUI JOIN:
 A join which is based on other than ‘=’ operator is called non-equi join.
 In non-equi join comparison operators such as !=,>,>=,<,<= are used to perform join.
Syntax: select table1.column_name1, table1.column_name2,…………..
from table1,table2
where table1.column_name!=table 2.column_name;
Example: Select emp.ename,dept.dname
From emp,dept
Where emp.deptno!=dept.deptno;

3) INNER JOIN:
 A Inner join will select all rows from both tables as long as there is match between the columns
Syntax: select *
from table1 INNER JOIN table2
ON table1.column_name=table 2.column_name;
Example: Select *
From emp INNER JOIN dept
ON emp.deptno=dept.deptno;

4) NATURAL JOIN:
 A Natural join combines data from two tables on the basis of common attributes equal values
 In natural join common attribute appear only once and appear as first attribute of result table
Syntax: select *
from table1 NATURAL JOIN table2
Example: Select emp.ename,dept.dname
From emp NATURAL JOIN dept

5) CROSS JOIN:
 A Cross join performs cartesian product operation(i.e cross join produces result in which
no. of rows in first table are multiplied by no. of rows in second table)
Syntax: select *
from table1 CROSS JOIN table2
Example: Select *
from emp CROSS JOIN dept

24
Database Management

6) SELF JOIN:
 The Self-join is used to join a table to itself.
Syntax: select a.column_name, b.column_name...
from table1 a, table1 b
where a.common_filed = b.common_field;

Example: find manager of each employee


Select a.ename “employee”, b.ename “manager”
from emp a,emp b
where a.mgr= b.empno;

7) OUTER JOIN:
 The outer join returns all rows from both tables which satisfy condition along with rows which do not
satisfy the condition.
There are three types of outer join
1. LEFT OUTER JOIN
A left outer join retains all of the rows of the “left” table, regardless of whether
there is a row that matches on the “right” table.
Syntax: select *
from table1 left outer join table2 on
table1.columnname= table2.columnname;

Example: select *
from emp left outer join dept on
emp.deptno=dept.deptno
2) RIGHT OUTER JOIN
A right outer join retains all of the rows of the “right” table, regardless of whether
there is a row that matches on the “left” table.
Syntax: select *
from table1 right outer join table2 on
table1.columnname= table2.columnname;

Example: select *
from emp right outer join dept on
emp.deptno=dept.deptno

3) FULL OUTER JOIN


A full outer join is a combination of left outer join and right outer join.
Syntax: select *
from table1 full outer join table2 on
table1.columnname= table2.columnname;

Example: select *
from emp full outer join dept on
emp.deptno=dept.deptno

25
Database Management

Sub Queries:
 The query written inside another query is called as sub query or
 We can write one select statement inside another select statement is called as sub queries or
nested queries.
Syntax:
Select *
From table_name
Where column_name operator (select column from table_name
where condition);

Type of sub queries:


1. Single row sub queries
2. Multiple row sub queries

1. Single row sub queries:


 Sub queries that returns single row are called single row sub queries
 Single row sub queries uses single row operators such as =,!=,>,>=,<,<=

Example 1: display details of employees whose job is same as that of employee no 7788
Select * from emp
Where job=(select job from emp where empno=7788)

Example 2: display details of employees whose salary is greater than salary of vijay
Select * from emp
Where sal>(select sal from emp where ename=’vijay’)

2. Multiple row sub queries:


 Sub queries that returns more than row are called multiple row sub queries
 Multiple row sub queries uses multiple row operators such as IN, ANY, ALL

Example 1: display details of employees whose salary is greater than minimum salary of
each department
Select * from emp
Where sal > ALL (select min (sal) from emp group by deptno)

Example 2: display details of employees whose salary is greater than minimum salary of
any department
Select * from emp
Where sal > ANY (select min (sal) from emp group by deptno)

Example 3: display details of employees whose salary is equal to minimum salary


of any department
Select * from emp
Where sal IN (select min (sal) from emp group by deptno)

26
Database Management

2.5 TCL (Transaction Control Language) Commands


 TCL commands are used to manage transactions in the database.
TCL commands are:
1. Commit:
 This command is used to permanently save database changes into hard disk of computer.
Syntax: Commit;
Example: insert into student values(1,’ram’,70);
insert into student values(2,’raj’,60);
commit;

2. Rollback:
 This command is used to undo the database changes up to last commit command.
Syntax: rollback;
Example: insert into student values(3,’ramesh’,50);
insert into student values(4,’rajesh’,80);
rollback;

3. Savepoint:
 This command is used to define breakpoints into transaction to enable partial rollback.
 Using rollback you can undo transactions upto last commit command but if you want to undo
transactions upto specific point then you need to first create savepoints into transactions and then
you can rollback transactions upto specific savepoint.
Syntax: savepoint savepoint_name;
Example: insert into student values(3,’ramesh’,50);
savepoint s1;
insert into student values(4,’rajesh’,80);
savepoint s2;
delete from student;
rollback to s1;

4.SET TRANSACTION:
 The SET TRANSACTION command can be used to initiate a database transaction
 the SET TRANSACTION command is used to set a transaction as read-only, set a transaction as
read/write and to assign name to a transaction,

Syntax: SET TRANSACTION [READ ONLY | READ WRITE] | [NAME ‘Transaction name’]
Parameters:
READ ONLY
Optional. If specified, it sets the transaction as a read-only transaction.
READ WRITE
Optional. If specified, it sets the transaction as a read/write transaction.
NAME
Assigns a name to the transaction identified by 'transaction_name' which is enclosed in quotes
Example:
Commit
Set transaction read only name ‘emp_clerk’
Select * from emp
Where job=’clerk’
order by sal desc;
Commit
The first COMMIT statement ensures that SET TRANSACTION is the first statement in the transaction.
The last COMMIT statement does not actually make permanent any changes to the database. It simply
ends the read-only transaction.

27
Database Management

Examples of SQL queries


Q.1. Consider the following structure for employee. The table EMP (Empno, Ename, Job, Mgr,
Joindates, salary, Comm, Deptno) Write SQL queries for the following :
(i) Display the list of employee excluding job title as ‘Salesman’.
(ii) Display the average salaries for each department.
(iii) Change the name of employee ‘Rahul Gosai’ to ‘Jigar Dave’,
(iv) Display employee details whose name start with ‘A’
Ans.:
i) select * from emp where job != ‘Salesman’;
ii) select avg(salary) from emp group by deptno;
iii) update emp set ename=’Jiger Dave’ where ename=‘Rahul Gosai’;
iv) select * from emp where ename like ‘A%;

Q.2. Consider the following database schema :


Emp (emp_no, ename, job, mgr, joindate, salary, comm., dept_no)
Solve the following queries in SQL :
i) Find the employees who belong to deptno 10 or 30.
ii) Find out number of employees who work as manager.
iii) Change the salary of employee “Prashant Sali” to 40000
iv) List all employees with null values for comm.. (i.e. commission)
Ans.:
i) Select * from emp where depot=10 or deptno=30;
ii) Select count(emp_no) from emp where job= ‘manager’;
iii) Update emp set salary=40000 where name =‘Prashant Sali’;
iv) select * from emp where comm IS NULL;

Q.3. Consider the structure of stud record (Name, Mark, Age, Place, Phone, Bith date).
Write SQL queries for following :
i) To list name of student who do not have a phone number.
ii) To list students from Nashik and Pune
iii) To change mark of Monika to 88 instead of 80.
iv) To list the students from Amit’s Age group.
Ans.:
i) select name from stud where phone IS NULL;
ii) select * from stud where city=’Nasik’ or city=’Pune’;
iii) update stud set mark=88 where name=’Monika’;
iv) select age from stud where age=(select age from stud where name=‘Amit’);

Q.4. Consider following structure for employee


EMP (empno, empname, job, mgr, joindate, salary, comm., dept.no)
Write SQL queries for the following :
1. To display annual salary of all employees.
2. To display name and salary for all employee whose salary is not in rage of Rs. 5000 and Rs.
10000.
Ans.:
1. select salary*12 from emp
2. select name, salary where salary not between 5000 and 10000;

Q.5. Consider the following database: Employee (emp_id, emp_name, emp_city, emp_addr,
emp_dept, join_date)
i) Display the names of employees in capital letters.
ii) Display the emp_id of employee who live in city Pune and Mumbai
iii) Display the details of employees whose joining date is after ’01-Apr-1997’.
iv) Display the total number of employees whose dept no. is ‘10’.

28
Database Management

Ans.:
i) select upper(emp_name) from emp;
ii) select emp_id from emp where city=‘Pune’ or city=‘Mumbai’;
iii) select * from emp where join_date> ‘01-Apr-1997’.
iv) Select count (emp_id) from emp where emp_dept=10;

Q.6 Given- Employee (EMP_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE,


DEPARTMENT)
Write SQL queries for-
i) Get FIRST_NAME, LAST_NAME from employee table.
ii) Get unique DEPARTMENT from employee table.
iii) Get FIRST_NAME form employee table using alias name “Employee Name”
iv) Get FIRST_NAME from employee table after removing white spaces from
left side.
Ans :
i) select FIRST_NAME,LAST,NAME from employee;
ii) select distinct DEPARTMENT from employee;
iii) select FIRST_NAME “Employee Name” from employee;
iv) select ltrim(FIRST_NAME) from employee;

Q.7 Consider following schema:


depositor (cust_name, acc_no)
borrower (cust_name, loan_no) Solve following Qeries:
(i) Find customer name having savings account as well as loan account.
(ii) Find customer names having loan account but not the saving account.
(Each query – 2 Marks)
Ans:
(i) Select cust_name from depositor intersect select cust_name from borrower;
(ii) Select cust_name from borrower minus select cust_name from depositor;

Q.8 Consider following schema:


Employee (emp_no, emp_name, dept, designation, salary, Dept_location)
Solve following queries:
(i) List all Managers in Mumbai location.
(ii) Set salary of all ‘project leaders’ to 70000/-.
(iii) List employees with having alphabet ‘A’ as second letter in their name.
(iv) Display details of those employees who work in Mumbai or Chennai.
(For each query - 1 Mark)
Ans:
i) Select * from Employee where designation= ‘Manager’ and Dept_location= ‘Mumbai’
ii) Update Employee set salary=70000 where designation= ‘project leader’
iii) Select * from Employee where emp_name like ‘_A’
iv) Select * from Employee where Dept_location= ‘Mumbai’ or Dept_location= ‘Chennai’

29
Database Management

Chapter 3: Advance features of SQL

View:
 The view is a virtual table based on another table.
 The table on which a view is based are called base table.
 The view does not contains its own data but it acts as window through which data from other tables
can be viewed or changed
 The view logically represents subset of data from one or more tables.
 The view takes output of query and treats it as a table.

Syntax to create view

1. Create view <view_name> as select statement;

2. Create or replace view <view_name> [Columns] as


Select statement
[With check option]
[With read only] ;
Parameters:
View_name: its unique name assigned to view
Replace: Re-creates view, if it’s already exists in database.
With check option: it specifies only row accessible to the view can be inserted, updated or deleted
through view.
With read only: it specifies view is only readable i.e. we can perform select operation on view, but we
. cannot perform insert, update or delete operation on view

Advantages of view
 View hides the complexity of database from other uses.
 View provides restricted data access from one or more tables.
 View does not require any extra storage space.
 View increases database performance.
 View can provide extra security from unauthorized users.
 View is used for security purpose.

Different options of view


 View can be a simple view, based on single table.
 View can be a complex view, based on more than one table.
 View can replace other view
 View can contain check constraint
 View can be read only

Simple view:
 Simple views based on single table.
Example 1:.Create view emp20 that contains details of employees in deptno 20.
Create view emp20 as
select * from emp where deptno = 20;

30
Database Management

Example 2:.Create view emp_vu20 that contains empno, empname, deptno of employees in deptno 20
from emp table and rename columns of view as eno,ename,dno respectively

Create or replace view emp_vu20 (eno,ename,dno) as


Select empno, empname, deptno from emp
Where deptno = 20;

Retrieving data from view :


 Data is retrieved from view as similar with data is retrieved from table.
 You can display either the contents of entire view or just specific rows and columns.
e.g. select * from emp20;

Creating complex view:


 Complex view, based on more than one table.
 Create complex view emp_dept_vu that contains empno, ename,deptno, dname columns from emp
and dept table
Create view emp_dept_vu as
Select empno, ename,emp.deptno, dname
from emp, dept
where emp. deptno = dept.deptno;

Removing view:
 We use drop view statement to remove the view from database.
 Drop view statement removes the view definition from database.

Syntax: drop view < view name >;

e.g. drop view emp_dept;

Example: Consider following schema: Depositor (Acc_no, Name, PAN, Balance)


Create a view on depositor having attributes (Acc_no, PAN) where balance is greater than
100000. (For command – 4 Marks)

Ans: Create view v1 as select Acc_no,PAN from Depositor where balance>100000;

31
Database Management

Sequence
 A sequence is a user created database object used to generate unique integer numbers
 Once sequence is created, it’s used for multiple tables.
 Sequence is generated and incremented or decremented by oracle routine.
 In oracle we can create auto number field using sequence.
Syntax to create sequence

Create sequence sequence_name [start with n] [increment by n]


[maxvalue n] [minvalue n] [cycle/nocycle][cache n/nocache]

Where,
sequence name:it is the name of sequence generator.
start with n: it specifies the first sequence number generated by sequence,( by default its 1)
increment by n: it specifies interval between sequence numbers,(i.e. it specifies number generated by
sequence is incremented by which number). (by default its 1)
maxvalue n: it specifies the maximum number generated by sequence (by default its 1027)
minvalue n: it specifies the minimum number generated by sequence (by default its 1)
cycle/nocycle:it specifies, continues to generate values after reaching its maximum or minimum
value,cycle means if number generated by sequence reach its maximum value then again it generates
number from minimum value
nocycle means if number generated by sequence reach its maximum value then it stops to generate
numbers and give error message to user (by default its nocycle)
cache n/nocache: cache n option specifies how many sequence values will be stored in cache memory
for faster access.
nocache means none of sequence value stored in cache memory.

Example: Create sequence with following specifications:


 Sequence name: empno_seq
 Starting value: 10
 Increment by: 2
 Maximum value: 100
 Minimum value: 5
 No cycle

Create sequence empno_seq start with 10 increment by 2 maxvalue 100


minvalue 5, nocycle;

Above example creates a sequence named empno_seq used for empno column of emp table, the sequence
starts at 10, does not cycle.
Use of sequence
 Sequence is used to generate unique integer numbers and that generated numbers are inserted as
values of primary key column in a table
 e.g To insert new record into emp table with empno generated from sequence empno_seq, ename as
raj and salary as 10000.
Insert into emp (empno, ename, sal)
values (empno_seq.nextval, ‘raj’, 10000);

32
Database Management

 To view or see current value for empno_seq sequence use following statement

Select empno_seq.currval from dual;

Modifying sequence :
 We can use alter sequence statement, to change increment value, maximum value, minimum value,
cycle/nocycle options of sequence.
 But with alter sequence statement we cannot change start with value of sequence.
Syntax to modify sequence
Alter sequence sequence_name [increment by n] [maxvalue n] [minvalue n]
[cycle/nocycle]

Example: Modify sequence named empno_seq with following specifications:


 Increment by: 5
 Maximum value: 200
 Minimum value: 2
 Cycle
Alter sequence empno_seq increment by 5, maxvalue 200,minvalue 2 cycle;

Removing a sequence
 We use drop sequence statement to remove the sequence from database.

Syntax : drop sequence <sequence_name>;


Example : drop sequence empno_seq;

Index :
 Index is a technique for faster searching of information from large table.
 Index used by the oracle server to speed up the retrieval of rows by using pointer.
 Indexes are logically and physically independent of the table they index.
 Indexs are used and maintained by oracle serves.
 Create index statement is used to create index on particular column of table.
Types of Index
1. Unique / Primary Index:
 It’s based on unique column of the table
 Unique index is created automatically when we define primary key or unique constraint at the time
of table creation.
Syntax : Create unique Index Index_name on table_name (coumn_name);
Example : To create unique index on empno column of emp table
Create unique Index emp_u on emp(emp_id);

2. Non-unique / Secondary/Simple Index:


 It’s based on non-unique column of the table
 User can create non-unique index on column to speed up access to row.
Syntax: Create Index Index_name on table_name (coumn_name);

Example: To create non-unique index on ename column of emp table


Create Index emp_s on emp(ename);

33
Database Management

3. Composite Index:
 It’s based two or more columns of table.

Syntax : Create Index index_name on table_name (column1, column2);

Example : To create composite index on job and salary columns of emp table
Create Index emp_c on emp( job,salary);

Removing Index :
 We use drop index statement to remove the index from database.

Syntax : Drop index <index_name>;

Example : Drop index emp_c;

Synonyms :
 Synonym is a alternative (alias) name given to table, view, sequence, function, procedure or
package
 It shortens lengthy object names.
 It simplifies access to object (another name to object)
 Synonyms are easy referring names given to table, view, function, procedure etc.
 Synonyms reduce complexity of SQL statement for database users.
 Synonyms are convenient or easy to use.
Creating Synonyms:
Syntax : Create synonym synonym_name for object name;

Example 1: To create short name e for employee table


Create synonym e for employee;

Example 2: To create short name e30 for emp_vu30 view


Create synonym e30 for emp_vu30;

 Synonym are used in DML statement in same way that the original relation is used
e.g. You can insert row in synonym e as you can insert row in employee relation.

Insert into e(empno, ename) values (1, ‘raj’);

Removing Synonym
To remove synonym from data dictionary use following statement

Syntax : Drop synonym <synonym_name>;

Example : Drop synonym e;

34
Database Management

Examples of SQL queries


Q1.Write SQL Commands to perform following operations on View.
i. Create a view to fetch enrollment_number, name, and percentage from student table and name it as S_View.
ii. Display record from S_View where percentage is greater than 60.
iii. Delete view named as S_view.
Ans:
i. Create view S_View as
Select enrollment_number, name, percentage from student;
ii. Select * from S_View
Where Percentage >60
iii. Drop view S_View

Q.2 Consider following schema:


Employee (emp_id, emp_name, job, hiredate, salary, comm, deptno)
Write SQL commands for following statements:
i. Create view emp_vu20 that contains details of employees in deptno 20
ii. Display employee details from view emp_vu20 whose salary is greater than 50,000
Ans:
i. Create view emp_vu20 as
Select * from Employee
Where deptno=20;
ii. Select * from emp_vu20
Where salary >50000

Q.3. Write SQL Commands to perform following operations on Sequence.


i. Create a sequence with following specifications.
 Name : DB_SEQ
 Starting Value : 1
 Maximum Value : 10
 Increment By: 2
ii. Modify a sequence named DB_SEQ with following specifications.
 Increment By: 3
 Maximum Value : 20
iii. Remove a sequence DB_SEQ from database
Ans:
i. Create sequence DB_SEQ start with 1 increment by 2 maxvalue 10
ii.Alter sequence DB_SEQ increment by 3 maxvalue 20
iii.Drop sequence DB_SEQ

Q.4 Write SQL Statement to perform following operation.


i. Create Synonym for Hotel table to HM.
ii. Create an Index on Hotel Table, use H_id as index attribute.
Ans:
i. Create Synonym HM for Hotel
ii. Create unique Index Hotel_u on Hotel(H_id)

Q.5. Consider following schema: student (rollno, name, class, dob,percentage)


Write SQL commands for following statements.
i. Create a shortened name stud for student table.
ii. Create a composite index on name and class columns.
Ans:
i. Create Synonym stud for student
ii. Create Index student_c on student(name,class)

35
Database Management

Chapter 4 : PL/SQL Programming


Introduction of PL/SQL :
 PL/SQL is a Procedural Language extension to SQL
 PL/SQL is developed by Oracle Corporation in 1990.
 PL/SQL is a powerful database programming language which allows user to write programs to
perform various operations on database.
 PL/SQL is an extension of SQL which provides features such as data encapsulation exception
handling, information hiding and also brings programming capability to the relational database.
 PL/SQL is a block structured language.

Advantages of PL/SQL :
1. Block Structures :
 PL/SQL consist of block of code.
 Each block forms unit of task
2. Procedural language capability :
 PL/SQL adds capabilities of procedural language like ‘C’
 PL/SQL consists procedural language constructs such as conditional statements, looping statements
and sequential statements.
3. Better performance :
 PL/SQL processes multiple SQL statements simultaneously as a single block.
4. Error Handling :
 PL/SQL handles errors or exceptions during program execution.
 If error occurs, PL/SQL display appropriate error message to users.

PL/SQL Data Types :


1. Number : For storing numeric data such as integer or floating point number.
e.g. A number;
2. Char : For storing character data. Char data type also used to store numbers or special symbols.
e.g. Name Char;
3. Varchar2 : For storing variable length character string, varchar2 data type also used to store
numbers or special symbols.
e.g. City Varchar2;
4. Date : For storing date and time.
e.g. Hiredate date;
5. Boolean : For storing Boolean values either true or false.
e.g. Flag Boolean;
7. LOB (Large Object) data type :
 It’s used to store large objects
 Large object can store either a binary or character data values upto 4GB in size.
The types of LOB are :
i. BLOB (Binary LOB) : It stores binary data upto 4GB in size, it stores binary data such as
videos or picture information.
ii. CLOB (Character LOB) :It stores character data upto 4GB in size,It stores character data
such as entire documents.
.

36
Database Management

7. % type: Declare variable that have same data type as that of a previously defined variables or columns
datatype in a table.
e.g. Z emp.sal%type;
Declares variable Z that have same data type as that of sal column of emp table

8. % Rowtype : It used to declare a composite variable that consist multiple sub variables inside it
as number of columns present in table and sub variables names and datatypes same as that of
column names and their datatypes in a particular table.
 % type refers columns data type whereas % rowtype refers all columns data types in a table
 % rowtype it declare variable that represents a row in a table.
 e.g. emp_rec emp%rowtype;
 You declare a record named emp_rec, its fields have same names and same data types as the
columns in emp table. You use dot notation to refer fields such as emp_rec.ename.

Display PL/SQL Output :


 The procedure dbms_output.put_line( ) is used to place the results in buffer.
 If we execute set serveroutput on command then SQL*PLUS retrieves and displays the contents of
buffer.
PL/SQL Block Structure :

Declare
Declaration of variables, constants, etc.
Begin
SQL executable statements;
PL/SQL executable statements
[exception]
Error handling code;
End;

Fig. : PL/SQL block structure


Basic unit in any PL/SQL program is a block the PL/SQL block consist of four main sections:
1. Declare Section:
 It consists of declaration of all variables, constants, cursors and etc. that are used in executable
sections.
2. Begin Section:
 It consists of set of SQL and PL/SQL executable statements to manipulate data from database.
 The PL/SQL program logic is written here, constructs like loops, conditional statements and SQL
statements are written here.
3. Exception Section:
 It consists code (set of statements) that is executed when run rime error occurs during the execution
of program.
 or It consists actions to be performed when error or abnormal conditions occurs during the
execution of PL/SQL code.
4. End Section :
 This section is used to make the end of PL/SQL block.

37
Database Management

Variables :
 Variables are used to store temporary data during PL/SQL program execution.
 Value of variable can be changed during program execution.
 Variables are declared in declare section of PL/SQL block.
Syntax for declaring variable in PL/SQL is as follows:
Variable_name datatype := initial value;
e.g. a number : = 10;
name char : = ‘Raj’;
Assigning value to variable :
The value can be assigned to the variable in any one of following two ways.
1. Using assignment operator :=
e.g. a: = 10;
2. Selecting table data values into variable
e.g. select ename into name
from emp
where empno = 7769;
Rules for declaring variable
1. Variable name must being with letter.
2. Variable length can be maximum 30 characters.
3. Space can’t be used in variable names
4. Case is insignificant while declaring variable.

Constants:
The constants are one whose value can’t be changed during program execution.
Syntax for declaring constant in PL/SQL is as follows::
Constant_name CONSTANT datatype : = defined value;
e.g. Pi CONSTANT number : = 3.14;
Y CONSTANT char : = ‘Hello’;

Fundamental components of PL/SQL :


1. Identifier : are names of PL/SQL objects as constants, variables, exceptions, functions, procedures
and reserved words.
2. Literals : are values of PL/SQL objects
e.g. a number : = 10

Identifier (variable) literal


3. Delimiter : are symbols with special meaning such as
: = (Assignment operator)
|| (concatenation operator)
; (Terminator for statements and declaration)
= (equality operator)
<< and >> Label delimiter
4. Comment : are section of code not execute by complier.
Comments are statements for user understanding purpose.
Single line comment begins with double hyphen (--)
Multiline comment begins with /* and ends with */

38
Database Management

Control Structure :
 The number of control statements can be used to change the logical flow of statements within
PL/SQL block.
PL/SQL provides following control structures:
1. Conditional Control:
 IF - Then statement
 IF – Then Else statement
 IF – Then Elsif statement’
 Case statement
2. Iterative control or looping statement:
 Simple loop statement
 While loop statement
 For loop statement
3. Sequential Control:
 Goto statement
 NULL statement
1.Conditional Control :
Conditional control executes specific condition given by user in program.
 IF - Then Statement:
- If- then statement executes sequence of statements if condition is true. If condition is false, then
if statement does nothing.
Syntax: If condition then
Sequence of statements;
End if;
 IF – Then Else statement
- It’s used to check condition, if the condition is true then sequence of statements written inside if
clause are executed. If condition is false then sequence of statements written inside else clause
are executed.
Syntax : If condition then
Sequence of statement 1;
Else
Sequence of statement 2;
End if;
 If- then Elsif statement:
- It’s used to check condition, if condition is true then sequence of statements written inside if
clause are executed.if condition is false, then elsif clause tests another condition. An if
statement can have any number of elsif clauses. conditions are evaluated one by one from top to
bottom.
- If any elsif condition is true, then its associated sequence of statements are executed and
control passes to next statement. If all conditions are false, then sequence of statements in else
clause are executed.
Syntax :If condition1 then
Sequence of statement1,
Elsif condition 2 then
Sequence of statement2,
Else Sequence of statementn+1
End if;

39
Database Management

 Case statement :
- The case statement selects one sequence of statements to execute.
- The case statement begins with keyword case followed by one or more when clauses.
-When clauses contains conditions. the conditions are evaluated sequentially. if any when condition
is true, then sequence of statements written in that when are executed.
-If any when clause is executed, control passes to next statement after end case, so subsequent
conditions are not evaluated.
-if no when condition is true then sequence of statements written in else clause are executed
Syntax :
Case
when condition1 then
sequence of statement1;
when condition2 then
sequence of statement2;
: :
when condition n then
sequence of statementn;
else
sequence of statementn+1;
end case;
e.g. Write a PL/SQL program to accept 3 numbers and display largest number.
Declare
a number : = &a;
b number : = &b;
c number : = &c;
Begin
if a > b and a > c then
dbms_output.put_line (‘A is largest number’);
elsif b > a and b > c then
dbms_output.put_line (‘B is largest number’);
elsif c > a and c > b then
dbms_output.put_line (‘C is largest number’);
else
dmbs_output.put_line (‘all numbers are equal’)
end if;
End;
2. Iterative control or looping statements:
- Loop statements execute sequence statements repeatedly multiple number of times.
There are three types of loop statements
.Simple Loop :
- Its used to repeat the sequence of statements multiple times.
- The exit when statement is used to terminate (exit) from loop.
- If exit when condition is true, then it terminates from loop and executes next statements after
end loop statement.
Syntax : loop
sequence of statements;
Exit when condition;
End loop;

40
Database Management

e.g. : Display numbers from 1 to 10 using loop statement


Declare
n number : = 1;
Begin
loop
dbms_output.put_line (n);
n:=n+1;
exit when n > 10;
End loop;
End;

While loop :
- The while loop is called conditional loop, it evaluates the condition before each loop executes,
- if condition written inside while is true ,then it executes sequence of statement written inside
while.
- if condition is false then it terminates loop and executes next statement after end loop
statement.

Syntax: While condition loop


Sequence of statements;
end loop;
e.g. Display numbers from 1 to 10 using while loop.
Declare
n number : = 1;
Begin
While n < = 10 loop
dbms_output.put_line(n);
n : = n+1;
end loop;
End;
 For loop :
- For loop is used to repeat sequence of statements multiple times.
- The statement written inside for loop executed until given condition is true.
- The counter changes from the lower bound to upper bound.
- If the reverse is specified then loop goes in reverse direction
Syntax :
For counter IN [Reverse] Lower bound..Upper bound loop
Sequence of statements;
end loop;
e.g. Display numbers from 1 to 10 using for loop
Declare
n number : = 1;
Begin
for n in 1 .. 10 loop
dbms_outpu.put_put_line (n);
end loop;
End;

41
Database Management

e.g. Display numbers 1 to 10 in reverse order using for loop


Declare
n number;
Begin
for n in reverse 1 .. 10 loop
dbms_output.put_line(n);
end loop;
End;
Examples of PL/SQL Programs:
1. Write PL/SQL program to perform addition of two numbers.
Declare
a number : = & a;
b number : = & b;
c number : = 0;
Begin
c : = a + b;
dbms_output.put_line(‘addition is’ ||c);
End;

2. Write PL/SQL program to find square of number


Declare
a number : = &a;
b number : = 0;
Begin
b : = a * a;
dbms_output.put_line(‘square of number’||b);
End;
3. Write PL/SQL program to find area of circle
Declare
r number : = &r;
pi CONSTANT number : = 3.14;
a number : = 0;
Begin
a : = pi * r * r;
dbms_output.put_line (‘the area of circle is’ ||a);
End;
4. Write PL/SQL code to check whether entered number is even or odd.
Declare
n number : = &n;
Begin
If mod(n,2)=0 then
dbms_output.put_line (‘number is even’);
else
dbms_output.put_line (‘number is odd’);
end if;
End;

42
Database Management

5.Write PL/SQL code to accept number from user and display factorial of number using while loop.
Declare
n number : = &n;
i number : = 1;
fact number : = 1;
Begin
While i < n loop
fact : = fact * 1;
i : = i + 1;
end loop;
dbms_outpu.put_line (‘factorial of number is’ ||fact);
end;
6. Write a PL/SQL program to find a raised to b
Declare
i number : = 1;
a number : = &a;
b number : = &b;
c number : = 1;
begin
for i in 1 .. b loop
c : = c * a;
end loop;
dbms_output.put_line(c);
end;
3. Sequential control structure :
It transfers flow of control sequentially up or down in PLSQL program.
 Goto statement:
- Its unconditional branching, when executed goto statement transfers flow of control to labeled
statement
Syntax :
goto label_name
…………….
……………..
<<label_name>>
Where, label_name is name of label and this goto label defined in program as above.
Example 1:
Declare
a number : = 1;
Begin
if a = 1 then
goto L1;
else
a : = 1;
end if;
<<L1>>
dbms_output.put_line (‘number is 1’);
End;

43
Database Management

Example 2: Begin
goto second_output;
dbms_output.put_line (‘hello’);
<<second_output>>
dbms_output.put_line (‘we are here’);
End;
Restrictions on goto statement :
1. Can branch out of if statement, loop or sub program
2. Can’t branch into an if statement or loop
3. Can’t branch from one section of an IF statement to another section
(i.e. branch from IF then section to else section is illegal)

 NULL Statement :
- Null statement does nothing; it passes control to next statement.
- It performs no action.
- We can use it to increase readability of your code.
e.g. Accept number from user, if number if 10 then display it, otherwise does nothing
Declare
n number : = &n;
Begin
if n = 10 then
dbms_output.put_line(n);
else
null;
end if;
End;
SQL Statements in PL/SQL :
 In PL/SQL blocks, DML statements such as select, insert, update and delete and TCL commands such
as commit, savepoint and rollback of SQL are used to extract information from or to apply changes to
the database. But DDL statements such as create table, alter table, drop table, truncate table, rename &
DCL statements such as grant, revoke are not supported by PL/SQL.
 Select statement in PL/SQL has following syntax
Select column_name into variable_name
From table_name
where condition
The select statement retrieves the single row value and store in variable using into clause.
For example:
declare
X emp.ename%type;
Y emp.job%type;
Z emp.sal%type;
begin
Select ename, job, sal into X, Y, Z from emp
where empno = 7369;
dbms_output_line (X || Y || Z);
end;
The insert, update and delete statements in PL/SQL are used in the same way as they are used in
SQL.

44
Database Management

Exception Handling:
 Exception means run time errors occurs during the execution of program.
 Exception handling means handling run time errors in program by writing set of statements in
exception section of PL/SQL block or
 Exception handling deals with errors that occur during execution of PL/SQL block.
There are two types of exceptions:
1. Predefined exceptions or system defined exceptions:
 Predefined exceptions are raised (called) automatically whenever corresponding error occurs during
execution of program.
Following are predefined PL/SQL exceptions:
1.NO_DATA_FOUND: Raised when select into or fetch statement returned no row.
2.TOO_MANY_ROWS: Raised when select statement returns more than one row.
3.ZERO_DIVIDE: Raised when we are trying to divide number by zero.
4.CURSOR_ALREADY_OPEN: Raised when we are trying to open cursor which is already open.
5.INVALID CURSOR: Raised when fetching row from closed cursor or closing cursor that is
not open.
6.CASE_NOT_FOUND: Raised when no when clause of case statement is selected and there is
no else clause.
7. VALUE_ERROR: Raised when value of variable is larger than declared size of variabl
Example 1: Write PL/SQL code that handles zero-divide exception:
Declare
a number : = 10;
b number : = 0;
c number : = 0;
begin
c : = a/b;
dbms_output.put_line(c)
when Zero_divide then
dbms_output.put_line (‘you are trying to divide number by zero’);
end;
2. User defined exception:
 User defined exceptions declared by user in declare section of PL/SQL block and raised explicitly
with raise statement in begin section of PL/SQL block and exceptions are handled within exception
section of PL/SQL block.
 Exception section includes different when clauses each with name of exception, followed by
sequence of statements to be executed when that exception is raised.
Structure of user defined exceptions handling:
Declare
exception_name exception;
begin
raise excetion_name;
Exception
when exception_name1 then
sequence of statement1;
when exception_name2 then
sequence of statement2;
when others then
sequence of statementn+1;
end;

45
Database Management

Example 2: Write PL/SQL code that handles Negative_sal user defined exception
Declare
Salary number (10, 2);
Negative_sal exception;
Begin
select sal into Salary from emp
where empno = 5;
if Salary < 0 then
raise negative_sal;
else
update emp set sal = 60000 where empno = 5;
end if;
Exception
when Negative_sal then
dbms_output.put_line (‘salary is negative’);
End;

Example 3 : Write PL/SQL code that handles multiple exceptions


Declare
Salary number (10, 2);
Negative_sal exception;
Begin
select sal into Salary from emp
where empno = 5;
if Salary < 0 then
raise negative_sal;
else
update emp set sal = 60000 where empno = 5;
end if;
Exception
when Negative_sal then
dbms_output.put_line (‘salary is negative’);
when No_data_found then
dbms_output.put_line (‘record not found’);
when Too_many_rows then
dbms_output.put_line (‘select statement returns multiple rows’);
when Value_error then
dbms_output.put_line (‘value of variable is larger than its defined length);
End;

46
Database Management

Cursor :
 Cursor is a temporary work area(memory) used to store data retrieved from database and
manipulate those data or
 Cursor can hold more than one row but can process only one row at a time.
 The select statement of PL/SQL is used when we want to access one row from table, but when we
want to access more than one row from table, then we need to use cursor.
 Cursors are used to executed SQL statement and store processing information.

There are two types of cursors in PL/SQL


1. Implicit Cursor
2. Explicit Cursor

1. Implicit Cursor:
 Implicit cursor created automatically when we execute DML statements like select, inserts, update,
delete. or
 Implicit cursors are declared by PL/SQL implicity for all DML statements.

There are four attributes associated with implicit cursor to obtain status information of cursor.
These attributes are as follows:
1.% FOUND : Returns true if an insert, update, delete statement affected one or more rows or
select into statement returns one or more rows, otherwise it returns false
e.g. SQL%FOUND

2.% NOT FOUND : Returns true if an insert, update, delete statement affected no rows or select
into statement returned no rows otherwise, it returns false.
e.g. SQL%NOT FOUND

3.% ISOPEN : It always returns false for implicit cursor, because oracle closes the SQL cursor
automatically after executing its associated SQL statement.
e.g. SQL%ISOPEN

4.% ROWCOUNT : Returns the number of rows affected by an insert, update or delete statement
or it returns number of rows returned by select into statement.
e.g. SQL%ROWCOUNT

Example 1: Write PL/SQL program to print number of rows deleted from emp table
or example of Implicit cursor
Declare
row_del number;
begin
delete from emp;
row_del := SQL%ROWCOUNT;
dbms_output.put_line (‘number of rows deleted are’ || row_del);
end;

47
Database Management

2. Explicit Cursor:
 Explicit cursor is user defined cursor.
 The explicit cursor is a select statement that is declared explicitly in declare section of PL/SQL
block and use open, fetch ,close statements in begin(execution) section of PL/SQL block.

Explicit cursor operations:


There are four operations that must be performed for successful working of cursor.
These operations are as follows:
1. Declare: Declare the cursor in declaration section using flowing syntax.
Syntax :
Cursor cursor_name is select statement
Here we give name to cursor and assign select statement to it.

2. Open : Open cursor in execution section


i.e. it executes select statement written in cursor definition.
syntax : Open cursor_name;

3. Fetch : Fetch data from cursor into PL/SQL variable in execution section.
i.e. Fetch statement places contents of current row into local variable.
Syntax : Fetch cursor_name into variable_name.

4. Close : Close the cursor in execution section before you end PL/SQL block. Closing a cursor
releases all resources used by cursor.
Syntax : Close cursor_name ;

Explicit cursor attributes:


There are four attributes associated with explicit cursor to obtain status information of cursor.
These attributes are as follows:
1.% FOUND : True, if fetch statement returns at least one row.
False, if fetch statement doesn’t return a row.
e.g. cursor_name%FOUND

2.% NOTFOUND : True, if fetch statement doesn’t return a row.


False, if fetch statement returns at least one row.
e.g. cursor_name%NOTFOUND

3.% ISOPEN : True, if cursor is already open in the program.


False, if the cursor is not opened in program.
e.g. cursor_name% ISOPEN

4.%ROWCOUNT:Return number of rows fetched by fetch statement .if no row is returned, the PL/SQL
statement returns an error.
e.g. cursor_name%ROWCOUNT.

48
Database Management

Example 2:Declare the cursor,that selects all records from emp table, after that inserts these records into
emp2 table (create new exmp2 table).
Declare
Cursor C is select * from emp,
X C%rowtype;
begin
Open C;
loop
Fetch C into X;
Exit when C%NOTFOUND;
insert into emp2
values (X.empno, X.ename, X.job, X.mgr, X.hiredate, X.sal, X.comm, X.deptno.);
End loop;
Close C;
End;

Example 3: With the help of cursor, increase salary with 20% for only those employees whose job
is clerk.
Declare
Cursor C1 is select empno from emp where job = ‘Clerk
X C1%rowtype;
begin
Open C1;
loop
Fetch C1 into X;
Exist when C1%NOTFOUND;
update emp set sal = sal+ sal*20/100;
where empno = X.empno;
End loop;
Close C1;
End;

Example 4:With the help of cursor display department number and names from dept table.
Declare
Cursor C2 is select deptno, dname, from dept;
X C2%towtype;
begin
Open C2;
loop
fetch C2 into X;
exit when C2%NOTFOUND;
dbms_output.put_line (X.deptno||X.dname);
end loop;
Close C2;
end;

49
Database Management

Trigger:
 The Trigger is a PL/SQL block that is executed automatically when an insert, update, delete
commands are executed.
 Trigger is PL/SQL block that executed implicitly by a DML statements.
 Trigger is a named database object that defines set of actions that are performed in response to
insert, update, delete operations against a table.
 Trigger are similar to stored procedure, but stored procedures are called explicitly and triggers are
called implicitly by oracle when the concerned even occurs.
Syntax for creating trigger :
Create or replace trigger trigger_name ………… trigger name
[before/after] ………… trigger timing
[insert/update/delete] ………… trigger event
on table_name ………… object name
[for each row/for each statement] ………… trigger type
PL/SQL block ………… trigger body
Components of Trigger :
1. Trigger name : It’s a unique name assigned to trigger.
2. Trigger timing : It indicates time when trigger fire.
3. Trigger event : It indicates DML operations that causes the trigger to fire.
4. Object name : It indicate the name of table to which trigger is associated.
5. Trigger type : It indicates the trigger type such as for each row or for each statement.
6. Trigger body : It indicate action performed by trigger.
Types of trigger :
1. Statement level trigger
2. Row level trigger
3. Before trigger
4. After trigger

1. Statement level trigger:


Statement level trigger is fired only once for DML statement irrespective of number of rows
affected by the statement. Statement level trigger is default type of trigger.
2. Row level trigger:
Row level trigger fired once for each row that is affected by DML statement.
e.g. If an update command updates 100 rows then row level trigger is fired 100 times whereas a
statement level trigger is fired only once.
3. Before trigger: This trigger is to be fired before DML command is executed.
4. After trigger: This trigger is fired after DML command is executed.
e.g. If after trigger is associated with inserts command then it’s fired after row is inserted into table.

Example 1. Create a trigger to store backup entry in backup_emp table, of every employee when the record
of his/her is deleted from the emp table.
Create or replace trigger deleted_emp after delete on emp
for each row
begin
insert into backup_emp(empno, ename, job, mgr, hiredate, sal, comm, deptno, resigndate)
values(:old.empno,:old.ename,:old.job,:old.mgr,:old.hiredate,:old.sal,:old.comm,:old.deptno,
sysdate);
end;

50
Database Management

Note that, before using this trigger, we have to create a table called backup_emp having columns similar
to those in emp table with one additional column which stores the date of resignation of employee called
resigndate.
When we compiler this PL/SQL block the trigger named deleted_emp get attached with delete operation
of emp table.
Now, if we execute following statement
delete from emp
where ename = ‘Raj’;
Then the information of employee Raj is deleted from emp table and is automatically stored in
backup_emp table.
Example 2. Create trigger trg1 that convert enames from lowercase to uppercase before inserting records
into emp table.

Create or replace trigger trg1


before insert on emp
for each row
begin
:new.ename : = upper (:new.ename);
end;
When, we complier this PL/SQL block, trigger trg1 is get attached with insert operation of emp table.
Now, if we execute following statement
insert into emp(ename) values(‘jayesh’);
then ename jayesh is converted into upper case before inserting into emp table.

Example 3. Create trigger emp_comm, that calculate commission 20% of their salary for every new
employee belonging to deptn 30 before record for that employee is inserted into emp table.
Create or replace trigger emp_comm
before insert on emp
for each row
begin
if :new.deptno = 30 then
: new.comm: = : new.sal*20/100;
end if;
End;
When, we compile this PL/SQL block, trigger emp_comm is get attached with insert operation of emp
table.Now, if we execute following statement
insert into emp Values (1, ‘Ajit’, ‘Salesman’, 7369, sysdate, 30000, null, 30);
Then trigger emp_comm is executed and calculates commission value 20% their salary for employee Ajit
befor inserting record into table emp.

Deleting Trigger :
To delete trigger from database drop trigger statement is used.
Syntax : drop trigger trigger_name;
Example drop trigger trg1;

51
Database Management

Functions:
 Functions are named PL/SQL blocks that can accept parameters, perform an action and returns a
value to calling program (environment).or
 Function is a subprogram that perform specific task
Advantages of Functions :
1. The main advantage of function is that it must return at least one value to calling program.
2. The functions are stored in database for repeated execution purpose.
3. Functions improve the performance of database
4. Functions can be called from another function or procedure
5. Functions can also be called from SQL statement.
The functions and procedures have same structure except that functions must have a return clause in the
header and at least one return statement in executable section.
Syntax for creating function :
Create or replace function function_name [(parameter1 [mode1] datatype1, ……)]
return datatype
IS/AS
PL/SQL block;
Mode parameters
IN : Which passes constant value from calling program into function or procedure
OUT : Which passes value from function or procedure to calling program.
IN OUT : Which Passes value from calling program function into function and passes different value
from function back to calling program.
Example 1.Write a function circle_area to find area of circle use radius as Input parameters
Create or replace function circle_area ( r in number)
return number
is
Pi constant number: = 3.14;
a number : = 0;
begin
a = pi * r * r;
return a;
end;
For calling above function, we write code as :
Declare
a number;
begin
a: = circle_area (5);
dbms_output.put_line (‘area of circle is’||a);
end;
Example 2. Write a function to count number of employees in a department function will accept a
department number & should return number of employees working in that department.
Create or replace function count_emp (dno number)
return number
is
X number;
begin
Select count (empno) into X from emp
where deptno = dno;
return X;
end;

52
Database Management

For calling above function, we write code as;


Declare
X number;
begin
X: = count_emp(10);
dbms_output.put_line (‘number of employee in department are ‘||X);
end;
Example 3.Create function that returns total number of employee in emp table.
Create or replace function total_emp
return number
is
total number;
begin
Select count (empno) into total from emp;
return total;
end;
for calling function, we write code as :
Declare
C number;
begin
c: = totalemp ( );
dbsms_output.put_line (‘total number of employee’|| C);
end;
When program calls a function, then program control is transferred to called function.
Then called function performs defined task and when it’s return statement is executed, then it return
program control back to main program.
Deleting Function:
To delete function from database drop function statement is used.
Syntax :Drop function function_name;
Example: Drop function totalemp;

Procedures:
 Procedures are named PL/SQL block that can accept parameters, perform an action and can be
invoked.
 Procedure is subprograms that perform a specific task.
 Procedures are stored in database for repeated execution purpose.
 Procedure does not return value to calling program, but with the help of out parameter it can return
multiple values to calling program.
Advantages of procedures:
1. Procedures improves the performance of database system because, once procedure is compiled
successfully, they are converted into machine executable versions of code and stored in database
for repeated execution. Whenever next time same procedure is called, then the database system
directly executes the procedure without recompiling it.
2. Procedures are stored in database for repeated executions.
3. Once procedures complied successfully it can be called from another procedure but it can’t be
called from function.
4. Stored procedures provided high level of security for data.
5. Stored procedures increases productivity by avoiding redundant coding.
53
Database Management

Syntax for creating procedure:


Create or replace procedure procedure_name [(parameter1 [mode1] datatype1, ….)
IS/AS
PL/SQL block;
Example 1.Write a procedure circle_area to find area of circle. Use radius as input parameter.
Create or replace procedure circle_area(r in number)
is
Pi constant number : = 3.14;
a number : = 0;
begin
a: = pi * r * r;
dbms_output.put_line (‘area of circle is ‘||a);
end;
Executing Procedure :
Procedure can be called in two ways :
1. Using execute keyword : execute circle_area (5);
2. Calling name of procedure from PL/SQL block begin.
begin
circle_area (5);
end;

Example 2. Write a procedure to count number of employees in a department. Procedure will accept a
department number and display number of employees working in that department.
Create or replace procedure count_emp(dno in number)
is
X number;
begin
select count (empno) into X from emp where deptno = dno;
dbms_output.put_line (‘no of employees in department are’|| X);
end;
Calling procedure :
begin
count_emp (10);
end;
Deleting a procedure :
To delete a procedure from database drop procedure statement is used.
Syntax : Drop procedure procedure_name;
Example: drop procedure circle_area;

Difference between function and procedure


Function Procedure
1.function must returns at least one value to calling 1. procedure does not return value to calling
program program
2.functions are used for computations 2.procedures are used for executing business logic
3.functions are slower than procedures because 3. procedures are faster than functions because
they are not stored in precompiled form they are stored in precompiled form
4.functions can be called from procedures 4. procedures can’t be called from functions
5.functions can be called from SQL statement 5.procedures can’t be called from SQL statement

54
Database Management

Chapter 5: Database security and Transaction processing


5.1 Introduction to Database security:
 Security is an important issue in database management because information stored in a database is
very valuable and sensitive resource of organization.so the data in database need to be protected from
unauthorized access and update and this is an important function of DBMS.
 Database security means protection of database from unauthorized access of data, modification of
data, and destruction of data.
 Security within DBMS protects integrity of data.
 Database security involves security of hardware, software, infrastructure, people and data of
organization.

Data Security Requirements

We should use technology to ensure a secure computing environment for the organization. Although it is
not possible to find a technological solution for all problems, most of the security issues could be
resolved using appropriate technology. The basic security standards which technology can ensure are
confidentiality, integrity and availability.

Confidentiality

A secure system ensures the confidentiality of data. This means that it allows individuals to see only the
data they are supposed to see. Confidentiality has several aspects like privacy of communications, secure
storage of sensitive data, authenticated users and authorization of users.

Privacy of Communications

The DBMS should be capable of controlling the spread of confidential personal information such as
health, employment, and credit records. It should also keep the corporate data such as trade secrets,
proprietary information about products and processes, competitive analyses, as well as marketing and
sales plans secure and away from the unauthorized people.

Secure Storage of Sensitive Data

Once confidential data has been entered, its integrity and privacy must be protected on the databases and
servers wherein it resides.

Authentication

One of the most basic concepts in database security is authentication, its process by which system verifies
a user's identity, A user can respond to a request to authenticate by providing a proof of identity, or an
authentication token

You're probably already familiar with concept. If you have ever been asked to show a photo ID (for
example, when opening a bank account), you have been presented with a request for authentication. You

55
Database Management

proved your identity by showing your driver's license (or other photo ID). In this case, your driver's
license served as your authentication token.

Despite what you see in the movies, most software programs cannot use futuristic systems such as face
recognition for authentication. Instead most authentication requests ask you to provide a user ID and a
password. Your user ID represents your claim to being a person authorized to access the environment,
and the password is protected and you are the only person who knows it.

Authorization

An authenticated user goes through the second layer of security, authorization. Authorization is the
process through which system obtains information about the authenticated user, including which database
operations that user may perform and which data objects that user may access.

A user may have several forms of authorization on parts of the database. There are the following
authorization rights.

• Read authorization allows reading, but not modification, of data.

• Insert authorization allows insertion of new data, but not modification of existing data.

• Update authorization allows modification, but not deletion of data.

• Delete authorization allows deletion of data.

Integrity

. Data integrity means data is protected from deletion and corruption, both while it resides within the
database, and while it is being transmitted over the network

Availability

A secure system makes data available to authorized users, without delay. Denial-of-service attacks are
attempts to block authorized users' ability to access and use the system when needed.

Types of Database Users:


The types of users and their roles and responsibilities depend on the database site. A small site can have
one database administrator who administers the database for application developers and users. A very
large site can find it necessary to divide the duties of a database administrator among several people and
among several areas of specialization.
Database Administrators
Each database requires at least one database administrator (DBA). An database system can be large and
can have many users. Therefore, database administration is sometimes not a one-person job, but a job for
a group of DBAs who share responsibility.

56
Database Management

A database administrator's responsibilities can include the following tasks:

 Installing and upgrading the Database server and application tools


 Allocating system storage and planning future storage requirements for the database system
 Creating primary database storage structures (tablespaces) after application developers have
designed an application
 Creating primary objects (tables, views, indexes) once application developers have designed an
application
 Modifying the database structure, as necessary, from information given by application developers
 Enrolling users and maintaining system security
 Controlling and monitoring user access to the database
 Monitoring and optimizing the performance of the database
 Planning for backup and recovery of database information
 Backing up and restoring the database
 Contacting DBMS vendor for technical support

Security Officers

An organization assigns one or more security officers to a database. A security officer enrolls users,
controls and monitors user access to the database, and maintains system security. if a company does not
have a separate security officer then the duties of security officers are performed by DBA

Network Administrators

Some sites have one or more network administrators. A network administrator can perform networking
related tasks, manage distributed databases and administer networking products

Application Developers

Application developers design and implement database applications. Application developers can perform
some of these tasks in collaboration with DBAs. Their responsibilities include the following tasks:

 Designing and developing the database application


 Designing the database structure for an application
 Estimating storage requirements for an application
 Specifying modifications of the database structure for an application
 Establishing security measures for an application during development

57
Database Management

Application Administrators

An database site can assign one or more application administrators to administer a particular application.
Each application can have its own administrator.

End Users
End users are users interact with the database through applications. A typical user's responsibilities
include the following tasks:
Entering, modifying, and deleting data, where permitted
Generating reports from the data
Creating, Altering and Deleting users:
A database may have many users. Each user has a user account. The job of database administrator is to
create new users, assign privileges to users, revoke privileges from users, alter users and delete users.
Create user: The create user command is used to create new user in a database.
Syntax: create user username identified by password;
Example: To create user abc having password abc123
create user abc identified by abc123;

Alter user: The alter user command is used to change password of user in a database.
Syntax: alter user username identified by new password;
Example: To change password of user abc to abc@123
alter user abc identified by abc@123;

Delete user: To delete a user from database drop user statement is used.
Syntax: drop user username;
Example: To delete user abc from database
drop user abc ;

58
Database Management

5.2 Protecting data within database-

• We can protect data from database using Authorization process

• Authorization means assigning privileges to user to access data from database.

• We can protect data from database by using: Privilege and Role

Database privileges

A privilege is a right(permission) to execute a particular type of SQL statement or to access another user's
object. Some examples of privileges include:

• The right to connect to the database (create a session)

• The right to create a table

• The right to select rows from another user's table

• The right to execute another user's stored procedure

Privileges are granted to users so that user can perform specific task.we should grant only required
privilege to user. Excessive granting of unnecessary privileges can lead to compromised security.

There are two types of privileges:

1. System privileges

System privileges are permissions to perform particular database operation. A system privileges are
normally granted by a DBA.
For example, to create a table, the user needs the create table system privilege.
Following are system privileges:
create session, create user, create table, create view, create sequence, create index, create procedure,
create trigger, alter any user, alter any table, alter any view, alter any sequence, alter any index, alter
any procedure, alter any trigger, drop any user, drop any table, drop any view, drop any sequence, drop
any index, drop any procedure, drop any trigger,etc

2. Object privileges

An object privileges are permissions to perform specific operations on a database objects such as table,
view, sequence, procedure, function. The object privileges are normally granted by owner of object.
For example, to insert data into emp table, the user needs insert object privilege.
Following are object privileges:
Select, insert,update,delete,execute

59
Database Management

Compare system privilege and object privilege.


system privilege object privilege
1.System privileges are permissions to perform 1. object privileges are permissions to perform
operation to manage database system. specific operations on a database objects such as
table, view, sequence, procedure, function
2. A system privileges are normally granted by a 2. The object privileges are normally granted by
DBA. owner of object.

3.examples of system privileges are: create session, 3. examples of object privileges are: Select,
create user, create table, create view,etc insert,update,delete,execute

4.syntax to assign system privileges: 4.syntax to assign object privileges:


Grant system privilege to username Grant object privilege on object_name to to
username
5.example to assign system privileges: 5.example to assign system privileges:
Grant create table to raj Grant insert on emp to raj

Granting and Revoking Privileges and Roles


We can grant (assign) privileges and roles to users using GRANT command and we can revoke (remove)
privileges and roles from users using REVOKE command.

The job of Database Administrators (DBAs) and Security Officers to grant privileges and roles to users
and to revoke privileges and roles from users

GRANT Command

The GRANT command is used to grant (assign) privileges users.

Syntax of GRANT command:

GRANT {ALL| privilege list} ON {object name} TO {user list | PUBLIC | Role_name} [WITH GRANT
OPTION]

Here, privilege list means list of privileges granted to users

If ALL is specified then all privileges granted to users

The ON clause is used to specify object name on which privileges are granted

The TO clause is used to specify users to whom privileges are granted

The PUBLIC is used to grant privileges to all users of the system.

The Role_name is used to grant privileges to role.

WITH GRANT OPTION means user has privilege to grant privileges to other users
60
Database Management

Examples of GRANT command:

1. Assign the SELECT privilege on BOOK table to all users

GRANT SELECT ON BOOK TO PUBLIC;

2. Assign ALL privilege on BOOK table to users ‘Vikas’ and ‘Rajan’

GRANT ALL ON BOOK TO Vikas,Rajan;

3. Grant the SELECT,INSERT authority with capability to grant those privileges to other users on
STUDENT table to user ‘Rajan’

GRANT SELECT, INSERT ON STUDENT TO Rajan WITH GRANT OPTION;

4. Give the system privileges for creating tables and views to ‘Rajan’

GRANT CREATE TABLE, CREATE VIEW TO Rajan

5. Grant the UPDATE authority on the SAL column of the EMP table to user 'AJAY'.

GRANT UPDATE (SAL) ON EMP TO AJAY;

REVOKE Command

The REVOKE command is used to remove (take out) the granted privileges from users.

Syntax of REVOKE command:

REVOKE {ALL| privilege list} ON {object name} FROM {user list | PUBLIC | Role_name}

Here, privilege list means list of privileges removed from users.

If ALL is specified then all privileges are removed from users.

The ON clause is used to specify object name from which privileges are removed.

The TO clause is used to specify users from whom privileges are removed.

The PUBLIC is used to remove privileges from all users of the system.

The Role_name is used to remove privileges from role.

Examples of REVOKE command:

1. Revoke the system privilege for creating table from 'Ajay'.


REVOKE CREATE TABLE FROM Ajay;
2. Revoke the SELECT privileges on EMP table from users ‘Ajay’ and ‘Rajan’.
REVOKE SELECT ON EMP FROM Ajay, Rajan;
3. Revoke the UPDATE privileges on EMP table from all users.
REVOKE UPDATE ON EMP FROM PUBLIC;
4. Remove ALL privileges on EMP table from user 'Ajay'.
REVOKE ALL ON EMP FROM Ajay;
61
Database Management

5. Remove DELETE and UPDATE authority on the SAL and JOB columns of the EMP table from
user 'Ajay'.
REVOKE DELETE, UPDATE (SAL, JOB) ON EMP FROM Ajay;

Roles

 Role is a group of privileges that can be granted to users. DBMS provide easy and controlled
privilege management through roles.

 If we want to assign same set of privileges to multiple uses, then we can create a role, grant privileges
to role and then grant role to users.

 The Privileges granted to Predefined roles are as follows

Predefined role Privileges granted to role

Connect create session, create table, create view, create sequence, create synonym, etc

Resource create table, create sequence, create procedure,create trigger

DBA All system privileges

Creating a role:
Syntax: Create role role_name;
For example: you have four clerk users: raj, ram, sunil, sagar in the database. To these users you want to
grant select, update privilege on emp table, select,delete privilege on dept table.
To do this first create a role by giving the following statement:
Create role clerks
Granting privileges to role:
Syntax: Grant privilege list on object name to role_name;
Then grant privileges to this role.
grant select,update on emp to clerk;
grant select,delete on dept to clerk;
Granting role to users:
Syntax: Grant role_name to users;
Now grant this clerk role to users like this
grant clerk to raj, ram, sunil, sagar;
Now raj, ram, sunil, sagar have all the privileges granted on clerk role.
Suppose after one month you want grant delete privilege on emp table to all these users then just grant
this privilege to clerk role.so automatically delete privilege on emp table is granted to all users.
grant delete on emp to clerk;

62
Database Management

Revoking privileges from role:


Syntax: Revoke privilege list on object name from role_name;
Example:If you want to take back update privilege on emp table from clerk role.
revoke update on emp from clerk;
Drop a role from the database
Syntax: Drop role role_name;
Example: If you want to drop role clerk from database
Drop role clerks;
5.3 Transaction processing and concurrency control :
The concept of Transaction
A transaction is a collection of operations that forms a single logical unit of work.
The transaction access data using two operations:
1. Read(x)-which reads data item x from database (hard disk) to local buffer (RAM)
2. Write(x)-which writes data item x from local buffer (RAM) to database (hard disk)
For Example: consider a transaction T1 transfers 100 rupees from account A to account B
This transaction can be defined as:
T1: Read (A);
A: =A-100;
Write (A);
Read (B)
B: =B+100;
Write (B);

ACID Properties:
1. Atomicity: Atomicity means either all operations of transaction performed completely or not at all.
In above transaction operations are Read (A), Write (A), Read (B) and Write (B);
Atomicity property says that either all of four operations of transaction executed at a time or
It should not execute any single operation of transaction.
2. Consistency: Consistency means after execution of transaction database remains in a consistent
state.
For e.g. suppose before execution of transaction T1 value of account A and account B balances are
1000 and 2000 respectively. The consistency property says that before execution of transaction sum
of A and B is 3000 then after execution of transaction sum of A and B must be 3000
3. Isolation: Even, if two transactions are executed concurrently its result must be same as when these
transactions are executed in some serial order.
4. Durability : Once transaction completes its execution successfully, the changes it has made to the
database remains as its even if there is system failure after the execution of transaction

63
Database Management

States of Transaction:

Fig. State diagram of transaction

The Transaction must be in one of following states


1. Active: The active state is initial state. The transaction starts its execution in active state
2. Partially Committed: When transaction completes execution of final statement then it enters into
partially committed state
3. Failed: Due to hardware failure or logical error the transaction can’t proceed its normal execution
then transaction enters into failed state.
4. Aborted: After unsuccessful completion of transaction, the transaction enters into aborted state
5. Committed: When transaction completes its successful execution then it enters into committed
state
Concurrent execution of transaction:
Concurrent Execution means more than one transaction executed at a same time.
Advantages of concurrent execution of transaction are as follows:
 Increased throughput: Throughput means number of transactions executed in given amount of time.
Due to concurrent execution of transactions the throughput is increases.
 Increase resource utilization: Due to concurrent execution of transactions, the utilization (use) of
resources such as processor and disk is increases.
 Reduced waiting time: Due to concurrent execution of transactions, the waiting time required for
short transactions is reduced.
If transactions run serially, then short transactions may have to wait for completion of long
transactions.

Schedules: The Schedule means order in which instructions from transactions are executed.
There are two types of Schedules:
1. Serial schedule
2. Concurrent schedule
1. Serial schedule: In serial schedule sequence of instructions from different transactions are executed
serially.
For Example: consider a transaction T1 transfers 50 rupees from account A to account B
This transaction can be defined as:
T1: Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);

64
Database Management

And transaction T2 transfers 10 percent of balance from account A to account B . This transaction can
be defined as:
T2: Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);
Suppose these two transactions T1 and T2 are executed one at a time in serial order of T1 followed by
T2.This execution sequence as shown in fig (a).

T1 T2
Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);

Fig (a).serial schedule T1 followed by T2.


Consider before execution of serial schedule T1 followed by T2 account A and account B balances are
1000 and 2000 respectively and Sum of A and B is 3000 then after execution of serial schedule T1
followed by T2 account A and account B balances are 855 and 2145 respectively and Sum of A and B
is 3000, so above serial schedule is consistent.
Suppose these two transactions T1 and T2 are executed one at a time in serial order of T2 followed by
T1.This execution sequence as shown in fig( b).

T1 T2
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+Temp;
Write (B);
Read (A);
A: =A-50;
Write (A);
Read (B)
B: =B+50;
Write (B);

Fig (b).serial schedule T2 followed by T1.


65
Database Management

Consider before execution of serial schedule T2 followed by T1 account A and account B balances are
1000 and 2000 respectively and Sum of A and B is 3000 then after execution of serial schedule T2
followed by T1 account A and account B balances are 850 and 2150 respectively and Sum of A and B
is 3000, so above serial schedule is consistent.
2. Concurrent schedule: In concurrent schedule sequence of instructions from different transactions
are executed concurrently (simultaneously).
Suppose two transactions T1 and T2 as defined above are executed concurrently.
This execution sequence as shown in fig (c).

T1 T2
Read (A);
A: =A-50;
Write (A);
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
B: =B+50;
Write (B);
Read (B)
B: =B+Temp;
Write (B);

Fig (c).Consistent concurrent schedule


Consider before execution of concurrent schedule account A and account B balances are 1000 and
2000 respectively and Sum of A and B is 3000 then after execution of concurrent schedule account A
and account B balances are 855 and 2145 respectively and Sum of A and B is 3000.so above
concurrent schedule is consistent.
Suppose two transactions T1 and T2 as defined above are executed concurrently.
This execution sequence as shown in fig (d).

T1 T2
Read (A);
A: =A-50;
Read (A);
Temp: =A*10/100;
A: =A-Temp;
Write (A);
Read (B)
Write (A);
Read (B)
B: =B+50;
Write (B);
B: =B+Temp;
Write (B);

Fig(d).Inconsistent concurrent schedule

66
Database Management

Consider before execution of concurrent schedule account A and account B balances are 1000 and
2000 respectively and Sum of A and B is 3000 then after execution of concurrent schedule account A
and account B balances are 950 and 2100 respectively and Sum of A and B is 3050.so above
concurrent schedule is inconsistent.
Lock-Based Concurrency control
Concurrency means multiple transactions access or change same data item at a same time.
In case of concurrent execution of transactions, consistency and isolation may not be maintained. So
to maintain consistency and isolation properties of transaction lock based concurrency control
schemes are used.
 Concurrency control means controlling concurrent access to data items.
Lock-Based protocol
 The lock based protocol is used for controlling concurrent access to data items.
 If two transactions want to access same data item at a same time then concurrency control manager
gives permissions for one transaction to access that data item through lock.
 Definition: LOCK is a mechanism that allows transactions to access data item only if it’s currently
holding a lock on that data item.
Types of locks (The data items locked in two modes)
1. Shared mode (S):
 In shared mode, transaction can read data item but can’t write data item.(i.e In shared mode only
select operation is allowed but insert, update and delete operations are not allowed)
 The multiple transactions can lock data item at a time in shared mode.

2. Exclusive Mode (X):


 In exclusive mode, the transactions can perform both read and write operations on data item. (i.e. In
exclusive mode select, insert, update and delete operations are allowed).
 The only one transaction can lock data item at a time in exclusive mode.
Lock Mode S X
S True False
X False False
Fig. Lock compatibility Matrix

From above lock capability matrix, we can say that shared mode is compatible with shared mode,
means at a same time two difference transactions make shared mode lock on same data item.
But shared mode is not compatible with exclusive mode; means if data item is already locked by
one transaction in shared mode and at the same time another transaction want to lock same data
item in exclusive mode then another transaction has need to wait until first transaction unlocks data
item.
 With the same reason, exclusive mode is not compatible with share mode and exclusive mode is not
compatible with exclusive mode.
 A transaction requests an shared lock on data item Q by executing the lock-S(Q) instruction and
similarly, a transaction requests an exclusive lock on data item Q by executing the lock-X(Q)
instruction. a transaction can unlock data item Q by the unlock(Q) instruction
 To access data item, transaction request lock in appropriate mode on data item to concurrency
control manager, if data item already locked by another transaction in an incompatible mode then
transaction need to wait until another transaction unlocks data item. If data item is not locked by
another transaction then lock can be immediately granted to transaction

67
Database Management

For Example: consider a transaction T1 transfers 50 rupees from account B to account A. This
transaction can be defined with lock based protocol as:
T1: lock-X(B);
Read (B);
B: =B-50;
Write (B);
Unlock (B);
lock-X(A);
Read (A)
A: =A+50;
Write (A);
Unlock(A);
And a transaction T2 display total balance of account A to account B . This transaction can be defined
with lock based protocol as:
T2: lock-S(A);
Read (A);
Unlock(A);
lock-S(B);
Read (B);
Unlock(B);
Display(A+B);
Suppose two transactions T1 and T2 as defined above are executed concurrently.
This execution sequence as shown in fig (e).
T1 T2 Concurrency control
manager
lock-X(B);
Grant-X(B,T1)
Read (B);
B: =B-50;
Write (B);
Unlock (B);
lock-S(A);
Grant-S(A,T2)
Read (A);
Unlock(A);
lock-S(B);
Grant-S(B,T2)
Read (B);
Unlock(B);
Display(A+B);

lock-X(A);
Grant-X(A,T1)
Read (A)
A: =A+50;
Write (A);
Unlock(A);

Fig (e). concurrent schedule with lock based protocol


Consider before execution of concurrent schedule account A and account B balances are 1000 and 2000
respectively and Sum of A and B is 3000 then after execution of concurrent schedule transaction T2
display sum of A and B as 2950, which is incorrect. The reason for this mistake is that the transaction T1
unlocked data item A too early, as a result of which T2 saw an inconsistent state.

68
Database Management

Two-Phase Locking Protocol


One protocol that ensures serializability is two phase locking protocol. This protocol requires that each
transaction issue lock and unlock requests in two phases:
1. Growing phase: In growing phase transactions may obtain locks, but not release any lock.
2. Shrinking phase: In shrinking phase transactions may release locks, but may not obtain any new
lock.
Initially, a transaction is in growing phase. In this phase transaction obtain locks as needed and once
the transaction releases a lock, it enters into shrinking phase and it can’t issue any more lock request
For Example: consider a transaction T1 transfers 50 rupees from account B to account A.This
transaction can be defined with two-phase locking protocol as:
T1: lock-X(B);
Read (B);
B: =B-50;
Write (B);
lock-X(A);
Unlock (B);
Read (A)
A: =A+50;
Write (A);
Unlock(A);
And a transaction T2 display total balance of account A to account B . This transaction can be defined
two-phase locking protocol as:
T2: lock-S(A);
Read (A);
lock-S(B);
Read (B);
Unlock(B);
Display(A+B);

T1 T2
lock-X(B);
Read (B);
B: =B-50;
Write (B);
lock-S(A);
Read (A);
lock-S(B);
lock-X(A);

Fig (f). Partial concurrent schedule with two phase locking protocol

Consider partial concurrent schedule with two phase locking protocol of figure (f) for T1 and T2. T1 is
holding an exclusive mode lock on B and T2 is requesting a shared mode lock on B, T2 is waiting for T1
to unlock B, similarly T2 is holding a shared mode lock on A and T1 is waiting for T2 to unlock A. Thus,
we have arrived at a state where neither of these transactions can ever proceed with its normal execution.
This situation is called deadlock. When deadlock occurs the system must rollback one of the two
transactions. Once a transaction has been rolled back, the data items that were locked by transaction are
unlocked. These data items are then available to other transaction, which can continue with its execution

69

You might also like