<<

PL/SQL

Database Management System – II

Chapter – 1

Query optimization

1. What is query processing in detail:  Query processing means set of activity that involves you to retrieve the  In other word we can say that it is process to breaking the high level language into low level language which machine understand and perform the requested action for user. Query processor in the DBMS performs this task.

 Query processing have three phase i. Parsing and transaction ii. Query optimization iii. Query evaluation  Lets see the three phase in details : 1) Parsing and transaction : 1 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. Check syntax and verify relations. . Translate the query into an equivalent . expression. 2) Query optimization : . Generate an optimal evaluation plan (with lowest cost) for the . 3) Query evaluation : . The query-execution engine takes an (optimal) evaluation plan, executes that plan, and returns the answers to the query

 Let us discuss the whole process with an example. Let us consider the following two relations as the example tables for our discussion;

Employee(Eno, Ename, Phone) Proj_Assigned(Eno, Proj_No, Role, DOP) where, Eno is Employee number, Ename is Employee name, Proj_No is Project Number in which an employee is assigned, Role is the role of an employee in a project, DOP is duration of the project in months. With this information, let us write a query to find the list of all employees who are working in a project which is more than 10 months old.

SELECT Ename FROM Employee, Proj_Assigned WHERE Employee.Eno = Proj_Assigned.Eno AND DOP > 10;

 Input: . A query written in SQL is given as input to the query processor. For our case, let us consider the SQL query written above.  Step 1: Parsing . In this step, the parser of the query processor module checks the syntax of the query, the user’s privileges to execute the query, the names and attribute names, etc. . The correct table names, attribute names and the privilege of the users can be taken from the system catalog ().  Step 2: Translation . If we have written a valid query, then it is converted from high level language SQL to low level instruction in Relational Algebra. 2 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. For example, our SQL query can be converted into a Relational Algebra equivalent as follows; . πEname(σDOP>10 Λ Employee.Eno=Proj_Assigned.Eno(Employee X Prof_Assigned))

 Step 3: Optimizer . Optimizer uses the statistical data stored as part of data dictionary. . The statistical data are information about the size of the table, the length of records, the indexes created on the table, etc. . Optimizer also checks for the conditions and conditional attributes which are parts of the query.  Step 4: Execution Plan . A query can be expressed in many ways. The query processor module, at this stage, using the information collected in step 3 to find different relational algebra expressions that are equivalent and return the result of the one which we have written already. . For our example, the query written in Relational algebra can also be written as the one given below; . πEname(Employee ⋈Eno (σDOP>10 (Prof_Assigned))) . So far, we have got two execution plans. Only condition is that both plans should give the same result.  Step 5: Evaluation . Though we got many execution plans constructed through statistical data, though they return same result (obvious), they differ in terms of Time consumption to execute the query, or the Space required executing the query. Hence, it is mandatory choose one plan which obviously consumes less cost. . At this stage, we choose one execution plan of the several we have developed. This Execution plan accesses data from the database to give the final result. . In our example, the second plan may be good. In the first plan, we two relations (costly operation) then apply the condition (conditions are considered as filters) on the joined . This consumes more time as well as space. . In the second plan, we filter one of the tables (Proj_Assigned) and the result is joined with the Employee table. This join may need to compare less number of records. Hence, the second plan is the best (with the information known, not always).

3 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

2. How to reduces cost of query  For query how many CPU cycle require  Communication cost  Disk operation  Centralized server/distributed data base

3. How to major cost of query 4. What is query optimization in details

 Introduction  Programming language/structured  It provide facility of procedural and function  It provides programming techniques like branching, looping, and condition check.  It is fully structured programming language.  It decreases the network traffic because entire block of code is passed to the DBA at one time for execution.  Basic Structure of PL/SQL . PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other. Typically, each block performs a logical action in he program. A block has the following structure:  DECLARE  /* Declarative section: variables, types, and local subprograms. */  BEGIN  /* Executable section: procedural and SQL statements go here. */  /* This is the only section of the block that is required. */  EXCEPTION  /* Exception handling section: error handling statements go here. */  END;

 Advantages of PL/SQL

4 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 PL/SQL is development too! that not only supports SQL data manipulation but also provide facilities of conditional checking, branching and looping.  PL/SQL sends an entire block of statements to the Oracle engine at one time. The communication between the program block and the Oracle engine reduces considerably. This is turn reduces network traffic. The Oracle engine gets the SQL statements as a single block, and hence it processes this code much faster than if it got the code one sentence at a time. There, is a definite improvement in the performance time of the Oracle engine. As an entire block of code is passed to the DBA at one time for execution, all changes made to the data in the table are done or undone, in one go.  PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly messages, when errors are encountered.  PL/SQL allows declaration and use of variables in blocks of code. These variables can be used to store intermediate results of a query for later processing, or calculate values and insert them into an Oracle table later. PL/SQL variables can be used anywhere, either in SQL statements or in PL/SQL blocks.  Via PL/SQL, all sorts of calculations can be done quickly and efficiently without the use of the Oracle engine. This considerably improves transaction performance.  Applications written in PL/SQL are portable to any computer hardware and operating system, where Oracle is operational. Hence, PL/SQL code blocks written for a DOS version of Oracle will run on its UNIX version, without any modifications at all.  Support for SQL  Support for object-oriented programming  Better performance  Higher productivity  Full portability  Tight integration with Oracle  Tight security o Disadvantage of pl . Disadvantages of Oracle PLSQLIf you're just running Oracle , there are no major disadvantages to using PL/SQL as long as you're aware of its

. limitations.Proprietary to OraclePL/SQL is proprietary to Oracle which means if you were to change database vendors then you would have to re-write all your

. Oracle PL/SQL programs. Also if you use a mixture of databases or develop applications to run on different databases, you will either have to support lots of

. source code or write your applications in a database-neutral language like Java, VB or C and use the APIs to access the database.Poor I/O FeaturesThe other

. behind this is that PLSQL is designed for manipulating information from the database and not for processing files or communicating with users. These operations 5 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 Data types  Rowid Datatypes

Data Type Explanation Oracle 10g Syntax (if applicable)

The format of the rowid is: BBBBBBB.RRRR.FFFFF Fixed-length binary data. Every record in the Rowid Where BBBBBBB is the database has a physical address or rowid. block in the database file; RRRR is the in the block; FFFFF is the database file. Universal rowid. Urowid(size) Where size is optional.

6 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 Character Datatypes

Data Type Explanation Oracle 10g Syntax (if applicable)

Where size is the number of characters to store. char(size) Maximum size of 2000 bytes. Fixed-length strings. Space padded.

Where size is the number of characters to store. nchar(size) Maximum size of 2000 bytes. Fixed-length NLS string Space padded.

Where size is the number of characters to store. nvarchar2(size) Maximum size of 4000 bytes. Variable-length NLS string.

Where size is the number of characters to store. Varchar2(size) Maximum size of 4000 bytes. Variable-length string.

Long Maximum size of 2GB. Variable-length strings. (backward compatible)

Raw Maximum size of 2000 bytes. Variable-length binary strings

Variable-length binary strings. (backward long raw Maximum size of 2GB. compatible)

 Numeric Datatypes

Data Type Explanation Oracle 10g Syntax (if applicable)

Where p is the precision and s is the scale. Precision can range from 1 to 38. number(p,s) Scale can range from -84 to 127. For example, number(7,2) is a number that has 5 digits before the decimal and 2 digits after the decimal. Where p is the precision and s is the scale. numeric(p,s) Precision can range from 1 to 38. For example, numeric(7,2) is a number that has 5 digits before the decimal and 2 digits after the

7 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

decimal. Where p is the precision and s is the scale. dec(p,s) Precision can range from 1 to 38. For example, dec(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal. Where p is the precision and s is the scale. decimal(p,s) Precision can range from 1 to 38. For example, decimal(3,1) is a number that has 2 digits before the decimal and 1 digit after the decimal.

 Date/Time Datatypes

Data Type Explanation Oracle 10g Syntax (if applicable)

A date between Jan 1, 4712 Date BC and Dec 31, 9999 AD. timestamp Includes year, month, day, hour, minute, and Fractional second’s precision (fractional seconds. must be a number between 0 seconds and 9. (default is 6) precision) For example: timestamp(6)

 Control structures  The flow of control statements can be classified into the following categories: . Conditional Control . Iterative Control . Sequential Control  Conditional Control . PL/SQL allows the use of an IF statement to control the execution of a block of code. . In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow specifying certain conditions under which a specific block of code should be executed. . Syntax: IF < Condition > THEN < Action > ELSIF THEN 8 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

< Action > ELSE < Action > END IF;

9 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. Example Using the IF-THEN-ELSEIF Statement DECLARE

a Number := 30;

b Number;

BEGIN

IF a > 40 THEN

b := a - 40;

DBMS_OUTPUT.PUT_LINE('b=' || b);

elsif a = 30 then

b := a + 40;

DBMS_OUTPUT.PUT_LINE('b=' || b);

ELSE

b := 0;

DBMS_OUTPUT.PUT_LINE('b=' || b);

END IF;

END;

/

 Iterative Control . Iterative control indicates the ability to repeat or skip sections of a code block. . A loop marks a sequence of statements that has to be repeated. The keyword loop has to be placed before the first statement in the sequence of statements to be repeated, while the keyword end loop is placed immediately after the last statement in the sequence. . Once a loop begins to execute, it will go on forever. Hence a conditional statement that controls the number of times a loop is executed always accompanies loops. . PL/SQL supports the following structures for iterative control: . Simple Loop

10 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 In simple loop, the key word loop should be placed before the first statement in the sequence and the keyword end loop should be written at the end of the sequence to end the loop. . Syntax: Loop < Sequence of statements > End loop;

11 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. Example: Create a simple loop such that a message is displayed when a loop exceeds a particular value. DECLARE i number := 0; BEGIN LOOP i := i + 2; EXIT WHEN i< 10; END LOOP; dbms_output.put_line ('Loop exited as the value of i has reached' || to_char (i)); END;  Output: Loop exited as the value of i has reached 12 PL/SQL procedure successfully completed.

. The WHILE loop . Syntax: WHILE LOOP < Action > END LOOP; . Example 3: Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 3 to 7. Store the radius and the corresponding values of calculated area in an empty table named Areas, consisting of two columns Radius and Area. . Table Name: Areas RADIUS AREA . CREATE TABLE AREAS (RADIUS NUMBER(5), AREA NUMBER(14,2));

DECLARE pi constant number(4,2) := 3.14 ; radius number(5); area number( 14,2); BEGIN radius := 3; 12 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

WHILE RADIUS <= 7 LOOP area := pi * power(radius,2); INSERT INTO areas VALUES (radius, area); radius := radius + 1; END LOOP; END; . After the loop is completed the table will now hold the following: Table Name: Areas RADIUS AREA 3 28.26 4 50.24 5 78.5 6 113.04 7 153.86

. The FOR Loop . Syntax: FOR variable IN [REVERSE] start..end LOOP < Action > END LOOP; . Note  The variable in the For Loop need not be declared. Also the increment value cannot be specified. The For Loop variable is always incremented by 1. . Example: Write a PL/SQL block of code for inverting a number 5639 to 9365. DECLARE given_number varchar (5) := '5639'; str_length number(2); inverted_number varchar(5); BEGIN Str_length := length(given_number); FOR cntr IN REVERSE 1..str_length /* Variables used as counter in the for loop need not be declared i.e. cntr declaration is not required */

13 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

LOOP inverted_number := inverted_number || substr(given_number, cntr, 1); END LOOP; dbms_output.put_line (The Given number is ' || given_number); dbms_output.put_line (The Inverted number is ' || inverted_number); END; . Output: The Given number is 5639 The Inverted number is 9365

 Sequential Control . The GOTO Statement  The GOTO statement changes the flow of control within a PL/SQL block.  This statement allows execution of a section of code, which is not in the normal flow of control.  The entry point into such a block of code is marked using the tags «userdefined name».  The GOTO statement can then make use of this user-defined name to jump into that block of code for execution. . Syntax:  GOTO ; . Example : Using a Simple GOTO Statement DECLARE p VARCHAR2(30); n number := 37; -- test any integer > 2 for prime BEGIN FOR j in 2..ROUND(SQRT(n)) LOOP IF n MOD j = 0 THEN -- test for prime p := ' is not a prime number'; -- not a prime number GOTO print_now; END IF; END LOOP; p := ' is a prime number'; <>

14 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

DBMS_OUTPUT.PUT_LINE (TO_CHAR(n) || p); END; /

Command:  The COMMIT command is the transactional command used to save changes invoked by a transaction to the database.  The COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command.  The syntax for COMMIT command is as follows:  COMMIT;

 ROLLBACK Command:  A ROLLBACK does exactly the opposite of COMMIT.  The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database.  The ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.  The syntax for ROLLBACK command is as follows:  ROLLBACK;

Command:  A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.  The syntax for SAVEPOINT command is as follows:  SAVEPOINT SAVEPOINT_NAME;  This command serves only in the creation of a SAVEPOINT among transactional statements.  The ROLLBACK command is used to undo a group of transactions.  The syntax for rolling back to a SAVEPOINT is as follows:  ROLLBACK TO SAVEPOINT_NAME;

 What are Cursors?

15 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. A is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.  There are two types of cursors in PL/SQL: . Implicit cursors:  These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. . Explicit cursors:  They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row. . Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed. Table 6.1: Cursor Attributes

Name Description %FOUND Returns TRUE if record was fetched successfully, FALSE otherwise. %NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise. %ROWCOUNT Returns number of records fetched from cursor at that point in time. %ISOPEN Returns TRUE if cursor is open, FALSE otherwise.

16 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 Implicit Cursors: . When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit statements are created to process these statements. . Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN. . For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected. . The status of the cursor for each of these attributes are defined in the below table. . For Example: Consider the PL/SQL Stock that uses implicit cursor attributes as shown below:  DECLARE Eid number(3); BEGIN UPDATE emp set eid=&eid where salary=&salary; eid:=sql%rowcount; IF SQL%found then dbms_output.put_line('success'); ELSe dbms_output.put_line ( ' not' ) ; END IF; dbms_output.put_line( 'rowcount'||eid); END;  Explicit Cursors . An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor. . The General Syntax for creating a cursor is as given below:  CURSOR cursor_name IS select_statement;  cursor _name -A suitable name for the cursor.  Select_statement - A select query which returns multiple rows.

17 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

. How to use Explicit Cursor?  There are four steps in using an Explicit Cursor.  DECLARE the cursor in the declaration section.  OPEN the cursor in the Execution Section.  FETCH the data from cursor into PL/SQL variables or records in the Execution Section.  CLOSE the cursor in the Execution Section before you end the PL/SQL Block.  Declaring a Cursor in the Declaration Section: DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000;  In the above example we are creating a cursor 'emp_cur' on a query which returns the records of all the employees.  employees with salary greater than 5000. Here 'emp_tbr in the table which contains records of all the employees.

 Accessing the records in the cursor:  Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program,

. How to access an Explicit Cursor?  These are the three steps in accessing the cursor.  Open the cursor.  Fetch the records in the cursor one at a time.  Close the cursor.

 General Syntax to open a cursor is: OPEN cursor_name;

 General Syntax to fetch records from a cursor is: FETCH cursor_name INTO record_name; OR FETCH cursor_name INTO variable_list;

 General Syntax to close a cursor is: 18 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

CLOSE cursor__name;

 When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the record or variables and the logical pointer moves to the next row and it becomes the current row. On every fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records.  Points to remember while fetching a row:  We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.  If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.  If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as the columns are present in the cursor.

. General Form of using an explicit cursor is: DECLARE variables; records; create a cursor; BEGIN OPEN cursor; FETCH cursor; process the records; CLOSE cursor; END;

. Lets Look at the example below  Example 1: DECLARE CURSOR er IS select eid,name from emp order by name ; id emp.eid%type; ename emp.name%type; BEGIN OPEN er; Loop 19 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

FETCH er into id,ename; Exit when er%notfound; dbms_output.put_line (id || ename); end loop; close er; END;

Parameterized cursor

PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to query.

PL/SQL Parameterized cursor define only data type of parameter and not need to define it's length.

Default values is assigned to the Cursor parameters. and scope of the parameters are locally.

Parameterized cursors are also saying static cursors that can passed parameter value when cursor are opened.

Following example introduce the parameterized cursor. following emp_information table,

Example :

Disadvantages of Oracle PLSQLIf you're just running Oracle databases, there are no major disadvantages to using PL/SQL as long as you're aware of its

limitations.Proprietary to OraclePL/SQL is proprietary to Oracle which means if you were to change database vendors then you would have to re-write all your

Oracle PL/SQL programs. Also if you use a mixture of databases or develop applications to run on different databases, you will either have to support lots of

source code or write your applications in a database-neutral language like Java, VB or C and use the APIs to access the database.Poor I/O FeaturesThe other

20 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

behind this is that PLSQL is designed for manipulating information from the database and not for processing files or communicating with users. These operationsSQL>set serveroutput on

SQL>edit parameter_cursor_demo

DECLARE

cursor c(no number) is select * from emp_information

where emp_no = no;

tmp emp_information%rowtype;

BEGIN

OPEN c(4);

FOR tmp IN c(4) LOOP

dbms_output.put_line('EMP_No: '||tmp.emp_no);

dbms_output.put_line('EMP_Name: '||tmp.emp_name);

dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);

dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);

END Loop;

CLOSE c;

END;

/

 Difference between pl and sql

21 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

-

 Locking protocol

 Locking protocole have 2 type of lock

i. shared lock (s) : shared lock mean if you give share lock to any transaction then you cant modifiy that transaction ,

 it is denoted by ‘s’

 in other words we can say that shared lock means only read not write

ii. Excusive lock : exclusive lock means if you give exclusive lock to any transaction you can read the transaction as well as you can modify the transaction too .

 it is denoted by ‘x’

 In other words we can say that shared lock mens read and write after lock

 Example :

22 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

T1 T2

Lock -(x) A lock <- x(A)

Read A read (A)

A= A-50 A= A-10

Write (a) Write (a)

Unclock (A) unlock (A)

 Compatable matrix of lock :

S X

S TRUE FALSE

FALSE FALSE X

 Shared lock to Shared lock

 If trasaction t1 is already given shared lock and then trasction t2 ask shared lock on t2 concerrancy control can give it .

 It is allowed shared lock to shared lock

 Shared lock to exclusive lock

 It is not allowed shared lock to exclusive lock

 If trasaction t1 is already given shared lock and then trasction t2 ask exclusive lock on t2 concerrancy control can not give it

 Exclusive lock to shared lock

 It is not allowed exclusive lock to shared lock

23 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 If trasaction t1 is already given exculsive lock and then trasction t2 ask shared lock on t2 concerrancy control can not give it

 Exclusive lock to exclusive lock

 It is not all exclusive lock to exclusive lock

 If transaction t1 is already given exclusive look and then trasaction t2 ask exclusive lock on t2 concerrancy control can not give it

 Example :

 Let A and B ne two amount that are accessed by transaction T1 and T2.

 Transaction T1 trasfers 50 from accout B to account A it is shown in T1

 T2 display the total amount of money in accounts A and B it is shown in below . it is shown in T2

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);

T2: Lock-S(A);

Read (A)

Unlock (A);

Read(B);

Unlock(B);

Display(A+B);

24 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)

PL/SQL

 Locking can lead to an undesirable situation : consider the schedual 1 of T1 . here T3 is holding an X mode lock on B and T4 is requesting a S mode lock on A and T3 is rrquesting an X mode lock on A , T3 is waiting for t4 unlock . A thus in this situation trasaction can proceeed with normal execution

 So this situation is called dead lock.

 When dead lock occurs , the system must roll back one of the two trasation has been rolled back , the data items that were locked by transaction are unlocked.

 These data items are then available to the other transaction , which can continue with its execution o Locking protocol:

 Each transaction in the system should follow a set of rules , called a lockin protocol, indicates when a transaction may lock and unlock each of the data items . locking protocol restrict the number of possible schedual . the set of all such schedules is a proper subset of all possible serializable schedual

25 PREPARED BY: RAHUL PATEL LECTURER IN COMPUTER DEPARTMENT (BSPP)