0% found this document useful (0 votes)
0 views

rohitjha_db,s[1][1][1]

The document outlines practical exercises in Database Management Systems, covering topics such as handling NULL values, pattern matching, update and delete statements, ordering query results, aggregate functions, and grouping results. It also discusses set operators, nested queries, joins, views, indexes, database security, and transaction control commands like commit and rollback. Each section includes syntax examples and explanations for various SQL operations and commands.

Uploaded by

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

rohitjha_db,s[1][1][1]

The document outlines practical exercises in Database Management Systems, covering topics such as handling NULL values, pattern matching, update and delete statements, ordering query results, aggregate functions, and grouping results. It also discusses set operators, nested queries, joins, views, indexes, database security, and transaction control commands like commit and rollback. Each section includes syntax examples and explanations for various SQL operations and commands.

Uploaded by

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

Database Management Systems Lab Rohit kumar

BTCS 505-18 2224525


Practical 03. Working with Null Values, Matching a Pattern from a Table,
Ordering the Result of a Query, Aggregate Functions, Grouping the Result of
a Query, Update and Delete Statements.

➢ Matching pattern for a Table :


• IS NOT Statement :- The IS NOT statement in DBMS is used in SQL to test if a
value does not match a specific condition, particularly when dealing with NULL
values. One of the most common uses of IS NOT is in conjunction with NULL, where
it checks whether a value is not null.

Syntax:- SELECT * FROM table_name

WHERE column_name IS NOT NULL;

Example:- select*from employees;

a. Query to retrieve id and name of employee whose salary in not null.

select id,name from employees where salary is not null;

b. Query to retrieve id and name of employee whose salary is null. select id,name

from employees where salary is null;

c. Display the employee details where name starts with “sh” select*from

employees where name like 'Sh%';

18
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
d. Display the employee details where “r” is a sub-string in the name.

select*from employees where name like '%a%';

e. Display id and salary of employee that must ended with “r”.

select id,salary from employees where name like '%r';

f. Display the employee details where name starts with “ar”. select*from

employees where name like '%ar';

g. Display the employee details in which the salary contain “500” in between.

select*from employees where salary like '%500%';

19
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

➢ Update pattern :- In DBMS (Database Management System), the UPDATE


statement is used to modify existing records in a table. You can update one or more
columns in a row or multiple rows based on specified conditions. The basic syntax
and usage patterns vary slightly depending on the database system, but they follow a
similar structure.

Syntax :- UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Example :-

a. Update the salary of employee to “60000” where age is grate than 23.
update employees set salary = 60000 where age > 23;

select id,age,salary from employees;

b. Update the salary of employee to “70000” where name are starting with “sh”.

update employees set salary = 70000 where name like 'Sh%';

20
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

select name,salary from employees where name like 'a%';

➢ Delete statement :- The DELETE statement in DBMS is used to remove one or


more rows from a table based on a specified condition. It allows you to delete specific
rows, or all rows in the table if no condition is provided.
Syntax :- DELETE FROM table_name

WHERE condition;

Example :-

➢ Ordering the Result of a Query :- In DBMS (Database Management


Systems), the result of a query can be ordered using the ORDER BY clause in SQL.
This allows you to sort the results based on one or more columns, either in ascending
or descending order.

Syntax :- SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

Example :-

a. Display the name and salary of employee based on decreasing order of their salary.

SELECT name, salary FROM employees ORDER BY salary DESC;

21
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

b. Display id and name of employee as per increasing order of employee id.

SELECT id, name FROM employees ORDER BY id ASC;

➢ Aggregate Functions :- Aggregate functions in DBMS (Database Management


Systems) are used to perform calculations on a set of values and return a single value.
They are commonly used in conjunction with the GROUP BY clause to group rows
that have the same values in specified columns and to summarize data.

22
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
Common Aggregate Functions :-

a. count ( ) :- Returns the number of rows that match a specified criterion.

Example :

SELECT COUNT(*) AS total_employees FROM employees;

b. sum ( ) :- Returns the total sum of a numeric column.

Example :

SELECT SUM(salary) AS total_salary FROM employees;

c. avg ( ) :- Returns the average value of a numeric column.

Example :

SELECT AVG(salary) AS average_salary FROM employees;

d. max ( ) :- Returns the maximum value in a set.

Example :

SELECT MAX(salary) AS highest_salary FROM employees;

e. min ( ) :- Returns the minimum value in a set.

Example :

23
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
SELECT MIN(salary) AS lowest_salary FROM employees;

➢ Grouping the Result of a Query :- In DBMS (Database Management


Systems), grouping the results of a query is accomplished using the GROUP BY
clause. This clause is often used in conjunction with aggregate functions to summarize
data by one or more columns. It allows you to group rows that have the same values in
specified columns into summary rows.

Syntax :- SELECT column1, aggregate_function(column2)

FROM table_name

WHERE condition

GROUP BY column1; Example :

Query to display name and salary of employee where age is grater than 20 and group by
salary.

SELECT salary, GROUP_CONCAT(fullname) AS employee_names FROM employees

WHERE age > 20 GROUP BY salary;

24
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

Practical 04. Set Operators, Nested Queries, Joins, Sequences.

➢ Set Operators :- Set operators in DBMS (Database Management Systems) are used
to combine the results of two or more SQL queries. These operators allow you to
perform operations similar to mathematical set theory, including union, intersection,
and difference.
Consider the following tables “department” and “customer” with following attributes id,name,
age, salary and email_ID in department table and id,name, age, address and salary in
customer table.

The most common set operators in SQL are :-

1. UNION :- • Combines the result sets of two or more SELECT statements


and removes duplicates.
• The columns in the SELECT statements must have the same data types and be in the
same order.

Syntax :- SELECT column1, column2, ...

FROM table1

UNION

SELECT column1, column2, ...

25
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
FROM table2;

Example :

select id,name,age from customer union select id name,age from department;

2. UNION ALL

• Similar to UNION, but it includes all duplicates. Use this when you want to see every
result from both queries.

Syntax :- SELECT column1, column2, ...

FROM table1

UNION ALL

SELECT column1, column2, ...

FROM table2; Example

select id name,age from customer union all select id,name,age from department;

26
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

3. INTERSECT

• Returns only the rows that are present in both result sets. It finds the common records
between two SELECT statements.

Syntax :- SELECT column1, column2, ...

FROM table1

INTERSECT

SELECT column1, column2, ...

FROM table2; Example : select id,fullname,age,salary from customer


intersect select id,fullname,age,salary from department;
4.EXCEPT (or MINUS in some SQL dialects)

• Returns rows from the first result set that are not present in the second result set. It is
useful for finding records that exist in one table but not another.

Syntax :- SELECT column1, column2, ...

FROM table1

EXCEPT

SELECT column1, column2, ...

FROM table2;

27
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
Example :

SELECT id name,age FROM department WHERE age >20 EXCEPT

SELECT id, name,age FROM customer WHERE salary > 20000;

PRACTICAL 5:

Views, Indexes, Database Security and Privileges: Grant and Revoke


Commands, Commit and Rollback Commands.

VIEWS:
A view in SQL is a virtual table that is based upon the result-set of an SQL Statement. A view will
also have rows and columns just like a real table in a database. Simply a view is nothing but a
stored SQL Query. A view can contain all the rows of a table or specific rows based on some
condition SQL functions conditions and join statements to a view and present the data just like the
data is produced from a single table.
Create a table student_detail with attributes student id, name, address .

Create 2nd table student_marks with attribute name , id, marks and age.

28
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

Simple view:
1. Query to create a view with attributes name and address where student id is < 104.
Syntax: Create view view_name as select column1, column2, ………….. from table_name
where condition;

29
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

Complex View:

2. Query to create a view having attributes name, address, marks where name is common
in both tables.
Syntax: create view view_name as select table1.col1,…table2.col1 from table1,table2
where condition;
Create view details2 as select studentdetail.name, studentdetails.address, student.marks
from studentdetails,studentmarks where studentdetails.name = studentmarks.name;

INDEXES:
An index is a data structure that allows us to add indexes in the existing table. It enables
you to improve the faster retrieval of records on a database table. It creates an entry for each value

30
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
of the indexed columns. We use it to quickly find the record without searching each row in a
database table whenever the table is accessed. We can create an index by using one or more
columns of the table for efficient access to the records.
CREATE INDEX:
To create indexes, we use the CREATE INDEX command. The syntax for the following is:
CREATE INDEX index_name ON table_name (column_name);

An index on multiple columns can also be created. When used for columns that are
frequently used together as filters, a multiple-column index performs better than multiple
single-column indexes.

EXPLAIN INDEXES:
If we want to see how MySQL performs internally, then “explain” command is
executed .The following syntax is used:

Syntax: mysql > explain select * from tablename;

SHOW INDEXES:
If we want to see the indexes of a table,then “show” command is executed. The following
Syntax is used :
Syntax: Mysql> show indexes from tablename;

DROP INDEXES:
Drop index command is used if a particular index has to be removed from a table. The
syntax is as followed:
31
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
Syntax: Mysql> drop index index_name on table_name;

GRANT COMMANDS:
The grant statement enables system administrators to assign privileges and roles to the
MySQL user accounts so that they can use the assigned permission on the database
whenever required.

CREATE USER: In order to grant privileges a user needs to be created. The new user can
be created by using CREATE USER command. The syntax for creating new user is : Create
user name@localhost identified by ‘password’;

GRANT specific privilege: In order to grant specific privileges like select, update,
insert, drop, delete, create, alter, update or index then the following syntax is executed:
Syntax: grant privilege_name on object to user_account_name;

SHOW GRANT : In MySQL, the SHOW GRANTS command is used to display all grant
information for a user. This would display privileges that were assigned to the user using
the GRANT command.The syntax is as follows:

Syntax: show grants for user_account_name;

32
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

GRANT ALL COMMAND: This command is used to assign all privileges to all databases
in the current server to user. The syntax used to assign all the privileges is :

Syntax: grant privilege_name on object to user_account_name;

REVOKE COMMANDS:
The revoke statement enables system administrators to revoke privileges and roles to the
MySQL user accounts so that they cannot use the assigned permission on the database in the
past.

REVOKE specific privilege :


Revoke command takes back or remove granted permission from the user. If specific
privileges are to be revoked like select, update, insert, drop, delete, create, alter, update or
index then the following syntax is executed:

Syntax: revoke privilege_name on object from user_account_name;

REVOKE ALL COMMAND: If we want to revoke or take back all privileges assign to the
user, execute the following statement:

Syntax: REVOKE privilege_name on object from user_account_name ;

33
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

COMMIT COMMAND:

MySQL databases offer support for database transactions by providing statements to initiate
these transactions. It gives us the following in-built queries:

START TRANSACTION :this query triggers the start of a transaction.

COMMIT: this query allows the changes made to the database to become permanent. You
can set your database to auto-commit changes by using the following query: Set
autocommit = 0;

SET: this query allows to set your commit by enabling the operations to commit
automatically or disabling the auto-commit. That is, the operations won't commit
automatically until the "commit" query is called.

To understand COMMIT query , a table “Children” is created having attributes id which


acts as primary key, name, percentage, location and Date of birth.

Before inserting the values in the table ,START TRANSACTION query is used which
triggers the strat of transaction.

34
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

Now, values are inserted into the table by using the following syntax:

Execute the SELECT query to verify that all the records are inserted successfully in the children
table.

DBMS LAB SHAINA SHARMA BTCS 505-18 2124479


We will commit our transaction to save all the changes permanently to the disk.

35
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
Now, turn off the auto-commit by setting the value of auto-commit as

0. Mysql> set autocommit = 0;

Then run a query to delete the child record whose ID is 5.

mysql> DELETE FROM student WHERE ID = 5;

To verify the results of the delete query, use the SELECT query.

Mysql> SELECT *FROM employee;

The child entry wih Id = 5 has been deleted ,now we wish to undo the changes we made to
the table then another comman called “Rollback” is used.
ROLLBACK COMMAND:

This query allows you to undo the changes you have made to the database, therefore
returning the database to its previous (last commit) state.

Execute the ROLLBACK command to get the original table that we have saved before
executing the delete command.

mysql> ROLLBACK;

36
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
Use SELECT Command to display the “children” table having attributes id, name,
percentage, location and date_of_birth .

The above results show that the student table containing five records is successfully
retrieved from the disk after using the rollback command.

Now, write a query to update the record and set the percentage as 99 for the student whose

ID is 1. mysql> UPDATE student SET Percentage = 99 WHERE ID = 1;

Here, this update query will be applied to the table which was retrieved after the rollback
command was put to use.

Use select command for the retrieval of the rows of table.

mysql> SELECT * FROM student;

37
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

Now, we will again rollback our transaction and execute the select query:

mysql> ROLLBACK;

mysql> SELECT * FROM student;

We can see that all the records are retrieved as they were earlier before applying the update
query.
PRACTICAL 6:

38
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL
Code, Referencing Non-SQL parameters.

PL/SQL ARCHITECTURE:

PL/SQL is Oracle’s procedural language extension to SQL. PL/SQL allows you to mix
SQLstatements with procedural statements like IF statement, Looping structures etc.
PL/SQL is thesuperset of SQL. It uses SQL for data retrieval and manipulation and uses its
own statements fordata processing. It was developed by Oracle Corporation in the early
90’s to enhance thecapabilities of SQL. Oracle uses a PL/SQL engine to processes the
PL/SQL statements. 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 development tools such as Oracle Form Builder, Oracle Reports
Builder etc.

Advantages of PL/SQL: PL/SQL has the following advantages:

• PL/SQL gives high productivity to programmers as it can query, transform, and


updatedata in a database.
• PL/SQL saves time on design and debugging by strong features, such as
exceptionhandling, encapsulation, data hiding, and object-oriented data types.
• Applications written in PL/SQL are fully portable.
• PL/SQL provides high security level.
• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for Developing Web Applications and Server Pages
WRITING PL/SQL CODE:

39
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

1. PL/SQL Code to print “hello”.

Syntax: begin
Dbms_output.put_line(‘hello’);
End;

2. PL/SQL Code to print the value of variable.

Syntax: declare

variable number:= value;

Begin

Dbms_output.put_line(‘variable_name’);

End;

CONDITIONAL CONTROL
Decision-making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed

40
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
if the condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.

1. IF - THEN statement: It is the simplest form of IF control statement, frequently


used indecision making and changing the control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by
the keywords, THEN and END IF. If the condition is TRUE, the statements get
executed, and if the condition is FALSE or NULL, then the IF statement does
nothing.

Syntax:

IF condition THEN S;

END IF;

2. IF-THEN-ELSE statement: A sequence of IF-THEN statements can be followed by


anoptional sequence of ELSE statements, which execute when the condition is
FALSE.

Syntax:

IF condition THEN S1; ELSE S2; END IF;

Where, S1 and S2 are different sequence of statements.

3. IF-THEN-ELSEIF statement: The IF-THEN-ELSIF statement allows you to choose


between several alternatives. An IFTHEN statement can be followed by an optional
ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements, there are few points to keep in mind. It’s
ELSIF, not ELSEIF.

SYNTAX:

IF condition1 THEN

Sequene of statements;

Elsif condition2 then

Sequence of

statements 2; Else

Sequence of statements 3;

41
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
END IF;

ITERATIVE CONTROL

A sequence of statements can be executed any number of times using the loop constructs.
The command is used with the EXIT command, which is responsible for interrupting the
LOOP execution. The LOOPS can be broadly classified into:

• SIMPLE LOOP STATEMENT


• WHILE LOOP STATEMENT
• FOR LOOP STATEMENT

A) SIMPLE LOOP STATEMENT:


Simple Loop Statement: Basic loop structure encloses sequence of statements in between
the LOOP and END LOOP statements. With each iteration, the sequence of statements is
executed and then control resumes at the top of the loop.

Syntax:

LOOP

Sequence of statements;

END LOOP;

42
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

B) WHILE LOOP STATEMENT


A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.

SYNTAX:-

WHILE condition LOOP

sequence_of_statements;

END LOOP

43
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

C) FOR LOOP STATEMENT :A FOR LOOP is a repetition control structure that allows
you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

FOR counter IN[REVERSE]initial_value .. final_value LOOP

sequence_of_statements;

44
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
END LOOP;
SEQUENTIAL CONTROL

Loop control statements change execution from its normal sequence. When execution
leaves ascope, all automatic objects that were created in that scope are destroyed.PL/SQL
supports thefollowing control statements. Labeling loops also helps in taking the control
outside a loop.

• GOTO STATEMENT: A GOTO statement in PL/SQL programming language


provides an unconditional jump from the GOTO to a labeled statement in the same
subprogram.

SYNTAX:

GOTO label;

statement;

45
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

• NULL STATEMENT: The Null statement explicitily specifies inaction; it does


nothing other than pass control to the next Statement.

Use: It can improve readability.

PRACTICAL 7:

Stored Procedures and Exception Handling.

STORED PROCEDURES:

A stored procedure is a prepared SQL code that you can save, so the code can be reused
over and over again. So, if you have an SQL query that you write over and over again, save
it as a stored procedure, and then just call it to execute it. You can also pass parameters to a
stored procedure, so that the stored procedure can act based on the parameter value(s) that
is passed.

BENEFITS OF STORED PROCEDURES:

• Reusable: As mentioned, multiple users and applications can easily use and reuse
stored procedures by merely calling it.
• Easy to modify: You can quickly change the statements in a stored procedure as and
when you want to, with the help of the ALTER TABLE command.
• Security: Stored procedures allow you to enhance the security of an application or a
database by restricting the users from direct access to the table.
• Low network traffic: The server only passes the procedure name instead of the
whole query, reducing network traffic.
• Increase performance: Upon the first use, a plan for the stored procedure is created
and stored in the buffer pool for quick execution for the next time.

SYNTAX FOR CREATING SIMPLE PROCEDURE:

PROCEDURE name(parameters)

Begin

//statements;

End;

46
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
SYNTAX FOR CALLING PROCEDURE:

Begin

Procedure_name(parameters);

End;

47
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
The output for the above procedure code is as follows:

EXCEPTION HANDLING:

Some errors are generated by the application at runtime. These errors can be generated
because ofvarious reasons and the application is not able to handle these errors, causing the
program to break and throw an exception. Usually, these are generated because of
unexpected human input such as passing an unexpected data type input e.g., passing an
integer at the place of a string value, dividing a number by zero, etc. But in real-life
scenarios, the program is not supposed to be broken down, but execute flawlessly.

Therefore, there is a need for a mechanism that can handle the situations that affect the
program’s normal execution or cause it to break. This mechanism is called exception
handling or error handling.

SQL Server also provides the exception handling mechanism like any other programming
language. There are different ways to handle the exceptions.

SYNTAX FOR EXCEPTION HANDLING:

DECLARE

exp exception;

pragma exception_init(exp,value);

BEGIN

48
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

//statements;

EXCEPTION

WHEN exp THEN

//statements;

END;

The output of the above code is as follows, it shows how the exception is handled:

PRACTICAL 8:

Triggers and Cursor Management in PL/SQL.

49
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

TRIGGERS:

A trigger is a named database object that is associated with a table, and that activates when
a particular event occurs for the table. Some uses for triggers are to perform checks of
values to be inserted into a table or to perform calculations on values involved in an update.

A trigger is defined to activate when a statement inserts, updates, or deletes rows in the
associated table. These row operations are trigger events. For example, rows can
be inserted by INSERT or LOAD DATA statements, and an insert trigger activates for
each inserted row.

Basic Commands

Creation

• CREATE TRIGGER
• Delete
• DROP TRIGGER :trigger name ;
• Show Trigger Code
• SHOW CREATE TRIGGER ; trigger name ;
• Show list of created Triggers
• SHOW TRIGGERS
• Call/execute a trigger
• We cannot call a trigger, like a procedure
• It is executed when an event happens call it

Designing a Trigger

• To design a trigger we have to determine:


• In which table it would be applied
• With what event it will be linked
• e.g. INSERT, UPDATE, DELETE
• When it will be executed
• Before the event
• After the event
• Its functionality
• At the main body of the trigger we can write SQL code

Trigger Creation Syntax:

CREATE TRIGGER trigger_name trigger_time trigger_event


ON table_name
FOR EACH ROW trigger_body

50
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
• trigger_name
• trigger_time ; When it will be executed (after or before)
• trigger_event ; the connected event
• ON table_name ; the table it belongs to
• FOR EACH ROW ; it will be executed for each row
• trigger_body ; the SQL scripts

Trigger Events

• The Triggers events could be


• INSERT
• UPDATE
• DELETE
• TRUNCATE &amp; DROP don’t call a Trigger
• We could have at max 6 triggers in every table

DROP TRIGGER :

Mysql> drop trigger database_name.trigger_name;

This statement drops a trigger. The schema (database) name is optional. If the schema is
omitted, the trigger is dropped from the default schema. DROP TRIGGER requires the
TRIGGER privilege for the table associated with the trigger.

CURSOR MANAGEMENT IN PL/SQL

51
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

To execute SQL statements, a work area is used by the Oracle engine for its internal
processing and storing the information. This work area is private to SQL’s operations. The
‘Cursor’ is the PL/SQL construct that allows the user to name the work area and access the
stored information in it.

USES OF CURSOR:
The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike
the SQL commands which operate on all the rows in the result set at one time. Cursors are
used when the user needs to update records in a singleton fashion or in a row by row
manner, in a database table. The Data that is stored in the Cursor is called the Active Data
Set. Oracle DBMS has another predefined area in the main memory Set, within which the
cursors are opened. Hence the size of the cursor is limited by the size of this pre-defined
area.

CURSOR ACTIONS

• Declare Cursor: A cursor is declared by defining the SQL statement that returns a
result set.
• Open: A Cursor is opened and populated by executing the SQL statement defined by
the cursor.
• Fetch: When the cursor is opened, rows can be fetched from the cursor one by one
or in a block to perform data manipulation.
• Close: After data manipulation, close the cursor explicitly.
• Deallocate: Finally, delete the cursor definition and release all the system resources
associated with the cursor.

SYNTAX FOR CURSOR IN PL/SQL :

52
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525
DECLARE
variables;
records;
create a
cursor;
BEGIN
OPEN
cursor;
FETCH
cursor;
process the
records;
CLOSE cursor;
END;

Working with Explicit cursor involves 4 major steps as following:


• Declaring the cursor for initializing the memory
• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

53
Database Management Systems Lab Rohit kumar
BTCS 505-18 2224525

54

You might also like