0% found this document useful (0 votes)
14 views9 pages

DBMS Ii 1

The document discusses transactions in databases, emphasizing the importance of ACID properties (Atomicity, Consistency, Isolation, Durability) and concurrency control mechanisms like locking protocols and deadlock handling methods. It also covers PL/SQL, its architecture, data types, and looping constructs, alongside examples of subqueries and aggregate functions. Overall, it provides a comprehensive overview of database transaction management and PL/SQL programming.

Uploaded by

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

DBMS Ii 1

The document discusses transactions in databases, emphasizing the importance of ACID properties (Atomicity, Consistency, Isolation, Durability) and concurrency control mechanisms like locking protocols and deadlock handling methods. It also covers PL/SQL, its architecture, data types, and looping constructs, alongside examples of subqueries and aggregate functions. Overall, it provides a comprehensive overview of database transaction management and PL/SQL programming.

Uploaded by

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

Transaction : A transaction can be defined as a group of tasks.

A single task is the minimum Locked based Protocol : In locked based protocol, each transaction needs to acquire locks
processing unit which cannot be divided further.Let’s take an example of a simple transaction. before they start accessing or modifying the data items. There are two types of locks used in
Suppose a bank employee transfers Rs 500 from A's account to B's account. This very simple and databases.
small transaction involves several low-level tasks.
Shared Lock : Shared lock is also known as read lock which allows multiple transactions to read
ACID Properties : Atomicity − This property states that a transaction must be treated as an the data simultaneously. The transaction which is holding a shared lock can only read the data
atomic unit, that is, either all of its operations are executed or none. There must be no state in a item but it can not modify the data item.
database where a transaction is left partially completed.
Exclusive Lock : Exclusive lock is also known as the write lock. Exclusive lock allows a transaction
Consistency − The database must remain in a consistent state after any transaction. No to update a data item. Only one transaction can hold the exclusive lock on a data item at a time.
transaction should have any adverse effect on the data residing in the database. If the database
was in a consistent state before the execution of a transaction, it must remain consistent after Timestamp based Protocol : In this protocol each transaction has a timestamp attached to it.
the execution of the transaction as well. Timestamp is nothing but the time in which a transaction enters into the system.The conflicting
pairs of operations can be resolved by the timestamp ordering protocol through the utilization
Durability − The database should be durable enough to hold all its latest updates even if the of the timestamp values of the transactions. Therefore, guaranteeing that the transactions take
system fails or restarts. If a transaction updates a chunk of data in a database and commits, then place in the correct order.
the database will hold the modified data.
Advantages of Concurrency : Waiting Time: It means if a process is in a ready state but still the
Isolation − In a database system where more than one transaction are being executed process does not get the system to get execute is called waiting time. So, concurrency leads to
simultaneously and in parallel, the property of isolation states that all the transactions will be less waiting time.Response Time: The time wasted in getting the response from the cpu for the
carried out and executed as if it is the only transaction in the system. first time, is called response time. So, concurrency leads to less Response Time.Resource
Utilization: The amount of Resource utilization in a particular system is called Resource
States of Transactions : A transaction in a database can be in one of the following states − Utilization.Efficiency: The amount of output produced in comparison to given input is called
efficiency. So, Concurrency leads to more Efficiency.

Disadvantages of Concurrency : Overhead: Implementing concurrency control requires


additional overhead, such as acquiring and releasing locks on database objects. Deadlocks:
Deadlocks can occur when two or more transactions are waiting for each other to release
resources, causing a circular dependency that can prevent any of the transactions from
completing. Complexity: Implementing concurrency control can be complex, particularly in
distributed systems or in systems with complex transactional logic.

Deadlock in DBMS : A deadlock is a condition where two or more transactions are waiting
indefinitely for one another to give up locks. Deadlock is said to be one of the most feared
complications in DBMS as no task ever gets finished and is in waiting state forever. For example:
In the student table, transaction T1 holds a lock on some rows and needs to update some rows
in the grade table. Simultaneously, transaction T2 holds locks on some rows in the grade table
and needs to update the rows in the Student table held by Transaction T1.
Active − In this state, the transaction is being executed. This is the initial state of every
transaction.

Partially Committed − When a transaction executes its final operation, it is said to be in a


partially committed state.

Failed − A transaction is said to be in a failed state if any of the checks made by the database
recovery system fails. A failed transaction can no longer proceed further.

Aborted − If any of the checks fails and the transaction has reached a failed state, then the
recovery manager rolls back all its write operations on the database to bring the database back
to its original state where it was prior to the execution of the transaction. Re-start the
transaction, Kill the transaction

Committed − If a transaction executes all its operations successfully, it is said to be committed. D


All its effects are now permanently established on the database system. eadlock Handling Methods : Deadlock Prevention: This approach aims to prevent deadlocks
from occurring by ensuring that at least one of the necessary conditions for deadlock cannot
Serializability : When multiple transactions are being executed by the operating system in a hold.
multiprogramming environment, there are possibilities that instructions of one transactions are
interleaved with some other transaction. Deadlock Detection and Recovery: In this method, deadlocks are allowed to occur, but
mechanisms are in place to detect them. Once detected, the DBMS can take action to resolve
Schedule − A chronological execution sequence of a transaction is called a schedule. A schedule the deadlock.
can have many transactions in it, each comprising of a number of instructions/tasks.
Deadlock Avoidance: Similar to prevention, but with a more dynamic approach. The system
Serial Schedule − It is a schedule in which transactions are aligned in such a way that one monitors the resource allocation and transaction execution dynamically and only grants a
transaction is executed first. When the first transaction completes its cycle, then the next resource request if it ensures that the system will remain deadlock-free.
transaction is executed. Transactions are ordered one after the other.
Deadlock Ignorance: Some systems simply ignore deadlocks altogether and rely on external
Concurrency Control in DBMS : Executing a single transaction at a time will increase the waiting intervention (like manual intervention or system restarts) to resolve them if they occur.
time of the other transactions which may result in delay in the overall execution.Concurrency
control is a very important concept of DBMS which ensures the simultaneous execution or Recovery Algorithm In DBMS : Deferred Update: In this approach, changes made by
manipulation of data by several processes or user without resulting in data inconsistency. transactions are kept in a buffer until the transaction reaches its commit point. Only then are
the changes permanently applied to the database.
Concurrency Control Problems : Dirty Read Problem(Write-Read conflict) : Dirty read problem
occurs when one transaction updates an item but due to some unconditional events that Immediate Update: Also known as Write-Ahead Logging (WAL), this approach immediately
transaction fails but before the transaction performs rollback, some other transaction reads the applies changes to the database but logs these changes in a separate log file before modifying
updated value. Thus creates an inconsistency in the database. the actual data.

Lost Update Problem : Lost update problem occurs when two or more transactions modify the Shadow Paging: This technique involves maintaining a shadow copy of the database, and only
same data, resulting in the update being overwritten or lost by another transaction. The lost updating the shadow copy. Once a transaction is committed, the changes are made permanent
update problem can be illustrated with the below scenario between two transactions T1 and T2. by updating the original database with the shadow copy.

1
Checkpointing/syncpoints/savepoints : Checkpoints are periodic events where the system Syntax to declare a constant : constant_name CONSTANT datatype := VALUE;
writes a snapshot of the database's current state to stable storage. This helps reduce recovery
time by providing a consistent starting point for the recovery process. Constant_name:it is the name of constant just like variable name. The constant word is a
reserved word and its value does not change.
Sub Query With Example : A subquery, also known as a nested query or inner query, is a query
nested within another query. It allows you to perform operations on the result set of another VALUE: it is a value which is assigned to a constant when it is declared. It can not be assigned
query. Here's an example of a subquery in SQL : Let's say we have two tables: employees and later.
departments. We want to find the names of employees who belong to the 'IT' department.

PL/SQL Architecture : The PL/SQL runtime system is a technology and not an independent
SELECT name product. This technology is actually like an engine that exhibits PL/SQL blocks, subprograms like
functions and procedures. This engine can be installed in an Oracle Server or in application
FROM employees development tools such as Oracle Form Builder, Oracle Reports Builder etc.

WHERE department_id = (SELECT department_id FROM departments WHERE


department_name = 'IT');

Types of subqueries in DBMS : Single Row Subquery: Returns zero or one row and one column.
It can be used with single-row operators like =, >, <, etc.

Example : SELECT name

FROM employees

WHERE salary > (SELECT AVG(salary) FROM employees);

Multiple Row Subquery: Returns multiple rows but only one column. It can be used with
multiple-row operators like IN, ANY, ALL.

Example : SELECT name PL/SQL can reside in two environments – The Oracle Server, The Oracle tools

FROM employees These two environments are independent of each other. In either environment, the PL/SQL
engine accepts any valid PL/SQL block as input. The PL/SQL engine executes the procedural part
WHERE department_id IN (SELECT department_id FROM departments WHERE location = 'New of the statements and sends the SQL statement executer in the Oracle Server.
York');
Advantages of PL/SQL : PL/SQL provides better performance. PL/SQL has high Productivity. It
Multiple Column Subquery: Returns multiple columns and multiple rows. It can be used in supports Object-Oriented Programming concepts. It has Scalability and Manageability. PL/SQL
conditions that require multiple values. supports various Web Application Development tools.

Example : SELECT name Disadvantages of PL/SQL : PL/SQL requires high memory. Lacks of functionality debugging in
stored procedures.

FROM employees
PL/SQL data types : 1.Scalar Data Types : CHAR/NCHAR: CHAR is a fixed-length character data
type, meaning it stores a specific number of characters regardless of the actual data length.
WHERE (department_id, salary) IN (SELECT department_id, MAX(salary) FROM employees
NCHAR is similar but stores fixed-length Unicode character data.
GROUP BY department_id);

VARCHAR2/NVARCHAR2: VARCHAR2 is a variable-length character data type, allowing storage


Nested Subquery : A subquery that contains another subquery within it.Can be nested to
of characters up to a defined maximum length. NVARCHAR2 is similar but stores variable-length
multiple levels.
Unicode character data.

Example : SELECT name


NUMBER: NUMBER is a numeric data type used for storing integers and decimals. It supports a
wide range of values, including fixed-point and floating-point numbers.
FROM employees

DATE: DATE data type stores date and time values in the format 'YYYY-MM-DD HH:MI:SS'. It can
WHERE department_id IN (SELECT department_id FROM departments WHERE location IN represent dates ranging from January 1, 4712 BC to December 31, 9999 AD.
(SELECT location FROM locations WHERE country_id = 'US'));

BOOLEAN: BOOLEAN data type represents logical values, typically TRUE, FALSE, or NULL.
What is PL/SQL : PL/SQL is a block structured language. The programs of PL/SQL are logical
blocks that can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural
2.Composite Data Types : TABLE: TABLE data type represents a collection of elements of the
Language extension of SQL" that is used in Oracle. PL/SQL is integrated with Oracle database
same data type, similar to arrays in other programming languages. It can be indexed by integers
(since version 7). The functionalities of PL/SQL usually extended after each release of Oracle
and can be used to store multiple values.
database.

VARRAY: VARRAY (Variable-Size Array) data type is an ordered collection of elements of the
PL/SQL Variables : A variable is a meaningful name which facilitates a programmer to store data
same data type with a maximum size specified at the time of declaration.
temporarily during the execution of code. It helps you to manipulate data in PL/SQL programs. It
is nothing except a name given to a storage area. Each variable in the PL/SQL has a specific data
type which defines the size and layout of the variable's memory. RECORD: RECORD data type is a composite data type containing a set of fields, each with its own
data type. It is similar to a structure or tuple in other programming languages.

How to declare variable in PL/SQL : You must declare the PL/SQL variable in the declaration
section or in a package as a global variable. After the declaration, PL/SQL allocates memory for 3.Reference Data Types : REF CURSOR: REF CURSOR data type is used to hold a cursor variable,
the variable's value and the storage location is identified by the variable name. allowing dynamic execution of SQL queries and processing result sets row by row.

Syntax for declaring variable : variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT 4.LOB Data Types : CLOB: CLOB (Character Large Object) data type is used for storing large
blocks of character data, such as text documents, in a database.

PL/SQL Constants : A constant is a value used in a PL/SQL block that remains unchanged
throughout the program. It is a user-defined literal value. It can be declared and used instead of BLOB: BLOB (Binary Large Object) data type is used for storing binary data, such as images,
actual values. audio files, or video files, in a database.

2
BFILE: BFILE data type is used for storing references to binary files that are stored outside the Syntax : LOOP
database, typically on the file system.
statements;
5.User-Defined Types (UDTs) : OBJECT: OBJECT data type allows users to define their own data
types with attributes and methods using the CREATE TYPE statement. These user-defined types EXIT WHEN condition;
can be used to represent complex data structures within PL/SQL programs.

END LOOP;
Looping And Iterations Statements of pl/sql :

Example : DECLARE
1.FOR Loop : The FOR loop iterates a specified number of times.

i NUMBER := 1;
Syntax : FOR loop_counter IN [REVERSE] lower_bound..upper_bound LOOP

BEGIN
statements;

LOOP
END LOOP;

DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);


Example : BEGIN

i := i + 1;
FOR i IN 1..5 LOOP

EXIT WHEN i > 5;


DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);

END LOOP;
END LOOP;

END;
END;

EXIT Statement : The EXIT statement is used to exit a loop prematurely based on a specified
Output : Iteration: 1 condition.

Iteration: 2 Syntax : EXIT [WHEN condition];

Iteration: 3 Example : DECLARE

Iteration: 4 i NUMBER := 1;

Iteration: 5 BEGIN

2.WHILE Loop : The WHILE loop iterates as long as a specified condition evaluates to TRUE. LOOP

Syntax : WHILE condition LOOP DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);

statements; i := i + 1;

END LOOP; EXIT WHEN i > 5;

Example : DECLARE END LOOP;

i NUMBER := 1; DBMS_OUTPUT.PUT_LINE('Loop exited.');

BEGIN END;

WHILE i <= 5 LOOP Output : Iteration: 1

DBMS_OUTPUT.PUT_LINE('Iteration: ' || i); Iteration: 2

i := i + 1; Iteration: 3

END LOOP; Iteration: 4

END; Iteration: 5

Output : Iteration: 1 Loop exited.

Iteration: 2 Aggregate Function : In SQL, an aggregate function is a function that operates on a set of values
and returns a single value summarizing the set. Common aggregate functions include SUM, AVG,
Iteration: 3 MIN, MAX, and COUNT. These functions allow you to perform calculations across multiple rows
of a table.
Iteration: 4
For example, you can use SUM to calculate the total of a column, AVG to find the average value,
Iteration: 5 MIN to get the smallest value, MAX to get the largest value, and COUNT to count the number of
rows that meet certain criteria. Aggregate functions are often used in conjunction with the
GROUP BY clause to group rows based on specific criteria before applying the aggregate
LOOP Loop : The LOOP loop is an infinite loop that continues until explicitly exited using an EXIT
function.
statement.

3
1. SUM: This function calculates the sum of values in a column. For example : ELSE

SELECT SUM(sales_amount) FROM sales; z:= y;

2. AVG: This function calculates the average of values in a column. For example : END IF;

SELECT AVG(sales_amount) FROM sales; END;

3. MIN: This function returns the minimum value in a column. For example : BEGIN

SELECT MIN(sales_amount) FROM sales; a:= 23;

4. MAX: This function returns the maximum value in a column. For example : b:= 45;

5. COUNT: This function returns the number of rows in a result set or the number of non-null findMin(a, b, c);
values in a column. For example : SELECT COUNT(*) FROM sales; -- Count all rows
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
SELECT COUNT(sales_amount) FROM sales; -- Count non-null values in the sales_amount column
END;
Grouping with Aggregate Functions: You can also use aggregate functions in conjunction with
the GROUP BY clause to group rows based on certain criteria before applying the aggregate Output : Minimum of (23, 45) : 23
function. For example, to find the total sales amount for each customer : SELECT customer_id,
SUM(sales_amount) AS total_sales
PL/SQL procedure successfully completed.

FROM sales
Positional Notation : In positional notation, you can call the procedure as − findMin(a, b, c, d);

GROUP BY customer_id;
In positional notation, the first actual parameter is substituted for the first formal parameter;
the second actual parameter is substituted for the second formal parameter, and so on. So, a is
Filtering with Aggregate Functions : You can filter the results of aggregate functions using the substituted for x, b is substituted for y, c is substituted for z and d is substituted for m.
HAVING clause, which is similar to the WHERE clause but specifically for filtering grouped results.
For example, to find customers with total sales amount greater than $1000 : SELECT
Named Notation : In named notation, the actual parameter is associated with the formal
customer_id, SUM(sales_amount) AS total_sales
parameter using the arrow symbol ( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
FROM sales

Mixed Notation : In mixed notation, you can mix both notations in procedure call; however, the
GROUP BY customer_id positional notation should precede the named notation. The following call is
legal − findMin(a, b, c, m => d); However, this is not legal : findMin(x => a, b, c, d);
HAVING SUM(sales_amount) > 1000;
Functions : A function is same as a procedure except that it returns a value. Therefore, all the
PL/SQL Procedure : The PL/SQL stored procedure or simply a procedure is a PL/SQL block which discussions of the previous chapter are true for functions too.
performs one or more specific tasks. It is just like procedures in other programming
languages.The procedure contains a header and a body.Header: The header contains the name Difference Between Function & Procedure :
of the procedure and the parameters or variables passed to the procedure.Body: The body
contains a declaration section, execution section and exception section similar to a general
PL/SQL block. Function Procedure

Parameter Modes in PL/SQL : IN : An IN parameter lets you pass a value to the subprogram. It is Functions always return a value after the The procedure can return a value using “IN
a read-only parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be execution of queries. OUT” and “OUT” arguments.
assigned a value. You can pass a constant, literal, initialized variable, or expression as an IN
parameter. In SQL, those functions having a DML A procedure can not be called using SQL
statement can not be called from SQL queries.
OUT : An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT statements.
parameter acts like a variable. You can change its value and reference the value after assigning it.
The actual parameter must be variable and it is passed by value. A Function can not return multiple result sets. A procedure is able to return multiple result
sets.
IN OUT : An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.The actual parameter
corresponding to an IN OUT formal parameter must be a variable, not a constant or an
expression. Formal parameter must be assigned a value. Actual parameter is passed by value.
The function can be called using Stored While procedures cannot be called from
Procedure. function.
IN & OUT Mode Example : DECLARE

a number; A function used only to read data. A procedure can be used to read and modify
data.

b number;
The function does not support try-catch Procedure supports try-catch blocks for error
blocks. handling.
c number;

A function can be operated in the SELECT While it can’t be operated in the SELECT
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
statement. statement.

BEGIN
Functions do not permit transaction It allows transaction management.
management.
IF x < y THEN

z:= x;

4
Types Of Functions : Scalar Functions: These functions return a single value. They are commonly Example Usage in Oracle : DECLARE cursor_name CURSOR SCROLL FOR
used for calculations, data transformations, and validation. Examples include functions to
calculate a sum, concatenate strings, or validate input data. SELECT column1, column2

Aggregate Functions: These functions operate on a set of rows and return a single result. FROM table_name;
Common aggregate functions include SUM, AVG, COUNT, MIN, and MAX. They are often used in
conjunction with the GROUP BY clause to perform calculations on groups of rows.
3.Static Cursor : A static cursor generates a static snapshot of the data when the cursor is
opened.Modifications to the underlying data do not affect the result set of the cursor. In other
System-defined Functions: These functions are built into the PL/SQL language or provided by words, changes made to the data after the cursor is opened do not affect the cursor. Example
the DBMS. Examples include functions for date manipulation (SYSDATE, ADD_MONTHS, Usage in MySQL:
TO_CHAR), string manipulation (SUBSTR, INSTR, UPPER), and mathematical calculations (ABS,
POWER, ROUND).
DECLARE cursor_name CURSOR STATIC FOR

User-defined Functions: These functions are created by users to perform custom operations.
SELECT column1, column2
They can encapsulate complex logic, calculations, or data manipulation tasks. User-defined
functions can be scalar or aggregate functions.
FROM table_name;
Deterministic Functions: These functions always return the same result when called with the
same input parameters. They are useful for caching and optimization purposes because the 4. Dynamic Cursor : A dynamic cursor reflects changes made to the underlying data while the
database engine can avoid re-evaluating the function if the input parameters haven't changed. cursor is open.This type of cursor is useful when you need to see real-time changes to the data
within the cursor. Example Usage in PostgreSQL :
Non-deterministic Functions: These functions may return different results for the same input
parameters, depending on factors such as database state, environment settings, or system DECLARE cursor_name CURSOR DYNAMIC FOR
variables. Examples include functions that rely on system time or random number generation.
SELECT column1, column2
Built-in Functions: These functions are provided by the DBMS to perform common tasks such as
mathematical calculations, string manipulation, date and time operations, and type conversions. FROM table_name;
They are part of the PL/SQL language and can be used directly in SQL queries and procedural
code.
Implicit Cursors: These are automatically created by Oracle when you execute a SQL statement
within a PL/SQL block. They are simple to use but offer limited control. Implicit cursors are
Importance / Advantages Of Packages : Modularity: Packages allow you to modularize your suitable for single-row queries.
code, making it easier to manage and maintain.

Ex : SELECT column_name INTO variable FROM table_name WHERE condition;


Encapsulation : They provide a way to hide implementation details, exposing only necessary
interfaces to other parts of the code.
Explicit Cursors: These are defined explicitly by the programmer. They offer more control and
flexibility compared to implicit cursors. Explicit cursors are suitable for handling multiple rows
Performance : PL/SQL packages can improve performance by reducing network traffic, as the and complex queries.
package specification is compiled and stored in the database once and can be reused by
multiple applications.
DECLARE

Name Space Control : Packages help in avoiding naming conflicts by providing a namespace for
CURSOR cursor_name IS
procedures, functions, and variables.

SELECT column_name FROM table_name WHERE condition;


Security : By granting appropriate privileges, you can control access to package elements,
enhancing security.
BEGIN

Code Reusability: Packages promote code reusability by allowing you to define common
functionality once and reuse it across multiple modules or applications. OPEN cursor_name;

Private Objects : Private objects are accessible only within the scope where they are declared. FETCH cursor_name INTO variable;
For example, a variable declared within a procedure or a function is private to that procedure or
function and cannot be accessed from outside. -- Process data

Public Objects :Public objects are accessible from any program unit within the same schema or CLOSE cursor_name;
from other schemas, depending on their visibility. For instance, procedures and functions
declared in a package specification are public by default and can be called from anywhere within END;
the same schema or from other schemas, granted necessary privileges.

Explicit cursors involve several steps: declaring the cursor, opening it, fetching data into
CURSOR : A CURSOR is a pointer or a handle to a result set returned by a SQL query. It allows variables, processing the data, and finally closing the cursor. They provide finer control over
you to iterate through the rows of the result set and process each row individually. Cursors are
result set manipulation and are essential for handling larger datasets or performing more
particularly useful when you need to work with query results row by row in a procedural
complex operations.
manner, rather than fetching the entire result set at once.

Cursor Attributes : 1. %FOUND : %FOUND returns TRUE if the last fetch operation successfully
Types Of Cursor : 1.Forward-only Cursor : This type of cursor allows you to traverse the result
retrieved a row, indicating that there are more rows to fetch.It returns FALSE if the last fetch
set only in a forward direction, meaning you can only move from the first row to the last operation failed to retrieve a row, either because there are no more rows or because the cursor
row.Once a record is fetched, it cannot be revisited. It's efficient for scenarios where you need is not yet opened. %FOUND is often used in loops to iterate over all rows returned by a cursor.
to process each row once and in order.

Example : IF cursor_name%FOUND THEN


Example Usage in SQL Server : DECLARE cursor_name CURSOR FOR

-- Process the fetched row


SELECT column1, column2

ELSE
FROM table_name;

-- No more rows to fetch


2.Scrollable Cursor : Unlike the forward-only cursor, a scrollable cursor allows traversal of the
result set in both forward and backward directions.This type of cursor provides more flexibility
in navigating through the result set. END IF;

5
2. %NOTFOUND: %NOTFOUND is the opposite of %FOUND. It returns TRUE if the last fetch /
operation failed to retrieve a row, indicating the end of the result set or if the cursor is not yet
opened.It returns FALSE if the last fetch operation successfully retrieved a row. %NOTFOUND is Exception: programming and database management, an exception is an event that disrupts the
commonly used to terminate loops when there are no more rows to fetch. normal flow of a program's execution. Exceptions are often caused by errors or unexpected
conditions that occur during runtime and can lead to abnormal program termination if not
Example : WHILE cursor_name%NOTFOUND LOOP handled properly.Exceptions provide a mechanism for detecting and responding to errors or
exceptional conditions in a controlled manner.
-- Process the fetched row
Types Of Exceptions : 1.Syntax Errors : These errors occur when the SQL query or statement
FETCH cursor_name INTO variable; violates the syntax rules of the DBMS.Common syntax errors include misspelling keywords,
missing or misplaced punctuation, or incorrect usage of SQL clauses.

END LOOP;
Example (SQL) : SELECT * FORM users; -- Syntax error: 'FORM' instead of 'FROM'

3. %ROWCOUNT: %ROWCOUNT returns the number of rows fetched so far by the cursor.It is
incremented by one each time a row is successfully fetched.%ROWCOUNT can be used to O/P : ERROR: syntax error at or near "FORM"
determine the total number of rows fetched or to implement pagination in result sets.
LINE 1: SELECT * FORM users;
Example : OPEN cursor_name;
2.Runtime Errors : Runtime errors, also known as exceptions, occur during the execution of a
FETCH cursor_name INTO variable; SQL statement due to unforeseen circumstances or incorrect data. Common runtime errors
include division by zero, constraint violations, and data type mismatches. Example (SQL) :
SELECT 1 / 0; -- Division by zero error
IF cursor_name%ROWCOUNT > 0 THEN

O/P : ERROR: division by zero


-- Process the fetched row

3.Constraint Violations : These errors occur when a SQL statement violates a constraint defined
END IF;
on the database schema, such as a primary key, foreign key, unique, or not null constraint.
Example (SQL) : INSERT INTO employees (id, name) VALUES (1, 'John');
4.%ISOPEN : %ISOPEN returns TRUE if the cursor is currently open, meaning it has been
declared and opened but not yet closed.It returns FALSE if the cursor is closed or if it has not
O/P : ERROR: null value in column "salary" violates not-null constraint
been opened yet.%ISOPEN is useful for checking the state of the cursor before attempting to
fetch rows or perform other operations.
Connection Failures : Connection failures occur when the DBMS is unable to establish a
connection with the database server.This can happen due to various reasons such as incorrect
Example : IF cursor_name%ISOPEN THEN
credentials, network issues, or the database server being unavailable. Example : import
psycopg2
CLOSE cursor_name;
try:
END IF;
conn = psycopg2.connect("dbname=mydb user=myuser password=mypassword")
Cursors With Sub Queries :
except psycopg2.OperationalError as e:
DECLARE
print("Unable to connect to the database:", e)
CURSOR emp_cursor IS
O/P : Unable to connect to the database: could not connect to server: Connection refused
SELECT employee_id, first_name, last_name
Database Triggers : Database triggers in PL/SQL are special procedures that are automatically
FROM employees executed or fired when certain events occur in the database. These events can include INSERT,
UPDATE, DELETE, or even DDL (Data Definition Language) statements like CREATE, ALTER, or
WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = DROP. Here's a basic structure of a PL/SQL trigger :
1700);
CREATE OR REPLACE TRIGGER trigger_name
emp_rec employees%ROWTYPE;
BEFORE/AFTER/INSTEAD OF event
BEGIN
ON table_name
OPEN emp_cursor; -- Open the cursor
[REFERENCING OLD AS old NEW AS new]
LOOP
[FOR EACH ROW]
FETCH emp_cursor INTO emp_rec; -- Fetch a row into emp_rec
DECLARE
EXIT WHEN emp_cursor%NOTFOUND; -- Exit loop when no more rows
-- Declarations
-- Process the fetched row
BEGIN
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_rec.employee_id);
-- Trigger logic
DBMS_OUTPUT.PUT_LINE('Name: ' || emp_rec.first_name || ' ' || emp_rec.last_name);
EXCEPTION
END LOOP;
-- Exception handling
CLOSE emp_cursor; -- Close the cursor
END;
END;

6
Types Of Triggers : BEFORE Triggers : These triggers are fired before the triggering statement /
(e.g., INSERT, UPDATE, DELETE) is executed.They can be used to validate data or perform actions
before the actual modification takes place.If a BEFORE trigger fails (raises an exception), the Statement-Level Triggers : These triggers are executed once for each triggering statement,
triggering statement is not executed. regardless of the number of rows affected.They cannot access the old and new values of
individual rows.Statement-level triggers do not include the FOR EACH ROW clause.
Before Trigger Example :Suppose we have a table called employees with columns id, name, and
salary, and we want to create a trigger that prevents updating the salary to a value less than the DML Operations: DML (Data Manipulation Language) operations in PL/SQL are used to
current salary. manipulate data stored in the database. The main DML statements in PL/SQL are :

CREATE OR REPLACE TRIGGER before_update_salary INSERT: Adds new rows of data into a table.

BEFORE UPDATE OF salary ON employees Example : INSERT INTO employees (employee_id, first_name, last_name, email)

FOR EACH ROW VALUES (101, 'John', 'Doe', '[email protected]');

BEGIN UPDATE: Modifies existing data in a table.

IF :NEW.salary < :OLD.salary THEN Example : UPDATE employees

RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased.'); SET salary = salary * 1.1

END IF; WHERE department_id = 10;

END; DELETE: Removes existing rows of data from a table.

/ Example : DELETE FROM employees

AFTER Triggers : These triggers are fired after the triggering statement has executed WHERE employee_id = 101;
successfully.They can be used to perform actions that depend on the results of the triggering
statement.AFTER triggers are commonly used for logging changes, auditing, or enforcing
Here's a PL/SQL block that demonstrates these DML operations :
business rules after the modification has occurred.

DECLARE
After Trigger Example : Suppose we have another table called audit_log to log all insertions into
the employees table, including the user who performed the insertion and the timestamp.
-- Declare variables
CREATE OR REPLACE TRIGGER after_insert_audit
v_employee_id employees.employee_id%TYPE;
AFTER INSERT ON employees
BEGIN
FOR EACH ROW
-- INSERT statement
BEGIN
INSERT INTO employees (employee_id, first_name, last_name, email)
INSERT INTO audit_log (username, action, timestamp)
VALUES (101, 'John', 'Doe', '[email protected]');
VALUES (USER, 'INSERT', SYSDATE);
-- UPDATE statement
END;
UPDATE employees
/
SET salary = salary * 1.1
INSTEAD OF Triggers :These triggers are used with views and are fired instead of the triggering
statement (usually INSERT, UPDATE, DELETE) on the underlying base tables.They are primarily WHERE department_id = 10;
used to enforce complex data manipulation rules on views.INSTEAD OF triggers allow you to
customize the behavior of the view, so when a DML operation is performed on the view, the -- DELETE statement
trigger logic is executed instead.

DELETE FROM employees


Row-Level Triggers : These triggers are executed once for each row affected by the triggering
statement.They can access both the old and new values of the affected row.Row-level triggers
WHERE employee_id = 101;
are defined with the FOR EACH ROW clause. Suppose we have a table called orders with
columns order_id, customer_id, order_date, and total_amount. We want to create a trigger that
automatically updates the order_date column with the current date whenever a new row is -- Commit the transaction
inserted into the orders table.
COMMIT;
CREATE OR REPLACE TRIGGER update_order_date
EXCEPTION
BEFORE INSERT ON orders
WHEN OTHERS THEN
FOR EACH ROW
-- Handle exceptions
BEGIN
ROLLBACK;
:NEW.order_date := SYSDATE;
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;

7
END; WHILE v_temp > 0 LOOP

DDL triggers, or Data Definition Language triggers, are special types of triggers in SQL that are v_digit := MOD(v_temp, 10);
fired in response to Data Definition Language (DDL) events such as CREATE, ALTER, and DROP
statements. Unlike regular triggers which respond to Data Manipulation Language (DML) events v_sum := v_sum + POWER(v_digit, 3); -- For a 3-digit Armstrong number
like INSERT, UPDATE, and DELETE, DDL triggers respond to changes in the structure of the
database schema.
v_temp := TRUNC(v_temp / 10);

Here's a basic structure of a DDL trigger :


END LOOP;

CREATE OR REPLACE TRIGGER trigger_name


IF v_sum = v_number THEN

BEFORE/AFTER ddl_event
DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is an Armstrong number.');

ON DATABASE
ELSE

[WHEN condition]
DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is not an Armstrong number.');

DECLARE
END IF;

-- Declarations
END;

BEGIN
/

-- Trigger logic
O/P : The number 153 is an Armstrong number.

EXCEPTION
3.Write Pl/SQL Block To Check Prime Or Not :

-- Exception handling
SET SERVEROUTPUT ON;

END;
DECLARE

1. Write Pl/SQL Block To Check Odd Or Even :


v_number NUMBER := 17; -- Change this to the number you want to check

SET SERVEROUTPUT ON;


v_is_prime BOOLEAN := TRUE;

DECLARE
BEGIN

v_number NUMBER := 10; -- Change this to the number you want to check
IF v_number <= 1 THEN

BEGIN
v_is_prime := FALSE;

IF MOD(v_number, 2) = 0 THEN
ELSE

DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is even.');


FOR i IN 2..ROUND(SQRT(v_number)) LOOP

ELSE
IF MOD(v_number, i) = 0 THEN

DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is odd.');


v_is_prime := FALSE;

END IF;
EXIT;

END;
END IF;

/
END LOOP;

O/P : The number 10 is even.


END IF;

2.Write Pl/SQL Block To Check Armstrong Or Not :


IF v_is_prime THEN

SET SERVEROUTPUT ON;


DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is a prime number.');

DECLARE
ELSE

v_number NUMBER := 153; -- Change this to the number you want to check
DBMS_OUTPUT.PUT_LINE('The number ' || v_number || ' is not a prime number.');

v_temp NUMBER := v_number;


END IF;

v_sum NUMBER := 0;
END;

v_digit NUMBER;
/

BEGIN
O/P : The number 17 is a prime number.

8
9

You might also like