Dma Notes
Dma Notes
Dma Notes
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
2
Database Management
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
Natural join ( )
Fig. Relational Algebra operations
3
Database Management
For example :
1. Select those tuples of loan relation where the branch is pune
3. Find those tuples of loan relation whose loan amount is greater than 3000 and whose branch is
Pune.
4
Database Management
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.
Result :
Cus_name
Sunil
Yash
Raj
Manish names who have either account or loan or both.
Fig. : Customer
5
Database Management
For e.g. 1 : Find the customer names who have both account and loan at the bank.
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
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)))
For e.g. (2) : Find names of customers who have taken loan from Pune branch.
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)
7
Database Management
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
Example:2 To modify data type of name column to varchar2 from student table
alter table student
modify (name varchar2(20));
9
Database Management
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.
10
Database Management
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
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);
12
Database Management
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
14
Database Management
4. Select: select command is used to display(retrieve) all or specific column from table
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
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
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;
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 ;
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’);
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
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:
19
Database Management
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
3. To_number : It converts character string containing a number into a number data type.
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
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;
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;
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
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);
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’)
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)
26
Database Management
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
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.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;
29
Database Management
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.
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.
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
Removing view:
We use drop view statement to remove the view from database.
Drop view statement removes the view definition from database.
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
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.
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
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]
Removing a sequence
We use drop sequence statement to remove the sequence from database.
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);
33
Database Management
3. Composite Index:
It’s based two or more columns of table.
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.
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;
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.
Removing Synonym
To remove synonym from data dictionary use following statement
34
Database Management
35
Database Management
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.
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.
Declare
Declaration of variables, constants, etc.
Begin
SQL executable statements;
PL/SQL executable statements
[exception]
Error handling code;
End;
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’;
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
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.
41
Database Management
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;
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.
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.
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 ;
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
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.
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
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
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;
54
Database Management
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.
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.
• Insert authorization allows insertion of new data, but not modification of existing 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.
56
Database Management
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:
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
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:
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.
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
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
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
GRANT {ALL| privilege list} ON {object name} TO {user list | PUBLIC | Role_name} [WITH GRANT
OPTION]
The ON clause is used to specify object name on which privileges are granted
WITH GRANT OPTION means user has privilege to grant privileges to other users
60
Database Management
3. Grant the SELECT,INSERT authority with capability to grant those privileges to other users on
STUDENT table to user ‘Rajan’
4. Give the system privileges for creating tables and views to ‘Rajan’
5. Grant the UPDATE authority on the SAL column of the EMP table to user 'AJAY'.
REVOKE Command
The REVOKE command is used to remove (take out) the granted privileges from users.
REVOKE {ALL| privilege list} ON {object name} FROM {user list | PUBLIC | Role_name}
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.
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.
Connect create session, create table, create view, create sequence, create synonym, etc
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
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:
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);
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);
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);
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);
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.
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);
68
Database Management
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