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

DBMS File

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

DBMS File

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Ram Devi Jindal Group of Institutions

Lalru, Mohali (140501)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Practical File

Subject Name: Database Management System

Subject Code: BTCS 505-18

SUBMITTED TO: SUBMITTED BY:


MR. DANISH NAME: AYUSH THAKUR
(Assistant Professor) ROLL NO: 2236316
CLASS & SEM:- B.TECH(CSE),5th

1|Page
INDEX
TASK EXPERIMENT PAGE REMARKS
NO.

1. Introduction to SQL and Installation of SQL Server 2-4


/ Oracle.

2. Data Types, Creating Tables, Retrieval of Row 6-10


using Select Statement, conditional retrieval of
Row, Alter and Drop statements.DBMS Practical:
Data Types, Creating Tables, Data Retrieval, and
Alter/Drop Statements.

3. Working with Null Values, Matching a Pattern 11-14


from a Table, Ordering the Result of a Query,
Aggregate Functions, Grouping the Result of a
Query, Update and Delete Statements.

4. Set Operators, Nested Queries, Joins, Sequences. 15-19

5. Views, Indexes, Database Security and Privileges: 20-23


Grant and Revoke Commands, Commit and
Rollback Commands.

6. PL/SQL Architecture, Assignments and 24-28


Expressions, Writing PL/SQL Code, Referencing
Non-SQL parameters.

7. Stored Procedures and Exception Handling. 29-32

8. Triggers and Cursor Management in PL/ SQL. 33-35

2|Page
TASK 1: Introduction to SQL and Installation of SQL Server / Oracle
1. Introduction to SQL (Structured Query Language)
SQL (Structured Query Language) is the standard language used to communicate with
relational databases. It is used for creating, managing, and manipulating databases and their
data. SQL commands are used for tasks such as querying data, updating records, creating
new databases, and setting up permissions.
Key Concepts in SQL:
1. Database: A collection of data that is organized in a structured way.
2. Table: Data in a database is organized into tables, consisting of rows (records) and
columns (fields).
3. Primary Key: A unique identifier for each record in a table.
4. Foreign Key: A column that creates a relationship between two tables.
5. Normalization: Organizing data to reduce redundancy and dependency.
Basic SQL Commands:
1. CREATE DATABASE: Used to create a new database.

2. CREATE TABLE: Used to create a new table within a database.

3. INSERT INTO: Used to insert new records into a table.

4. SELECT: Retrieves data from one or more tables.

5. UPDATE: Updates existing records in a table.

6. DELETE: Deletes records from a table.

7. ALTER TABLE: Modifies an existing table.

3|Page
8. DROP TABLE: Deletes a table and its data permanently.

9. WHERE: Used to filter records based on a specific condition.

10. JOIN: Combines rows from two or more tables based on a related column.

SQL Data Types:


 INT: Integer data type.
 VARCHAR: Variable-length string data.
 DATE: Date type.
 DECIMAL: Decimal numbers.

2. Installation of SQL Server


Steps to Install SQL Server (Using Microsoft SQL Server as an Example):
1. Download SQL Server:
o Visit the official Microsoft SQL Server download page: Download SQL Server.
o Select the version (e.g., SQL Server 2022 Developer Edition or SQL Server
Express).
2. Run the Installation Wizard:
o Once the SQL Server installer is downloaded, run it.
o Choose the "Basic" installation type or "Custom" for more control over the
setup.
o Accept the license terms.
3. Choose Installation Features:
o Select the necessary features for your needs (e.g., Database Engine Services,
SQL Server Replication, Full-Text and Semantic Search, etc.).
o Click Next.
4. Choose Instance Name:
o Choose the default or provide a custom instance name (e.g., SQLSERVER01).
o Click Next.
5. Set Authentication Mode:
o Choose the authentication mode. Windows Authentication is easier, but
Mixed Mode (SQL Server Authentication) is used for more flexibility.
o Set the SQL Server system administrator (sa) password if you select Mixed
Mode.
o Click Next.

4|Page
6. Choose Installation Location:
o Choose the directory where SQL Server will be installed (the default is
typically fine).
o Click Install.
7. Install:
o Click Next and allow the installer to complete the process. This may take
several minutes.
8. Launch SQL Server Management Studio (SSMS):
o Once the installation is complete, download and install SQL Server
Management Studio (SSMS) to manage your SQL Server instances.
o You can download SSMS from here.

3. Installation of Oracle Database


Steps to Install Oracle DBMS (Oracle Database 19c as an Example):
1. Download Oracle Database:
o Go to the official Oracle website and download Oracle Database 19c or the
version you prefer: Oracle Database Downloads.
o You will need an Oracle account to access the downloads.
2. Extract the Oracle Files:
o After downloading the ZIP or RPM files, extract them to a directory on your
system.
o On Linux, use unzip or rpm commands. On Windows, simply extract the zip
file.
3. Install Oracle Database:
o On Windows: Launch setup.exe from the extracted folder.
o On Linux: Run the Oracle Universal Installer by executing ./runInstaller in the
terminal.
4. Follow the Installation Steps:
o Accept the Oracle license agreement.
o Select the type of installation (e.g., Desktop Class, Server Class).
o Choose a directory for Oracle installation.
o Set Oracle system password.
o The installer will perform pre-installation checks.
5. Complete the Installation:
o The installer will begin installing Oracle Database. This may take some time.
o When prompted, run the script as root (on Linux).
o Once the installation is complete, Oracle will be ready for use.
6. Start Oracle Database:
o On Windows: Oracle services should start automatically.
o On Linux: Start the database manually using sqlplus or other Oracle tools.

4. Practical SQL Operations

5|Page
Example SQL Queries for Practice:
1. Creating a Database:

2. Creating a Table:

3. Inserting Data:

4. Querying Data:

5. Filtering Data:

6. Updating Records:

7. Deleting Records:

8. Joining Tables: Assuming there is a Courses table

6|Page
TASK 2: Data Types, Creating Tables, Retrieval of Row using Select Statement,
conditional retrieval of Row, Alter and Drop statements.
DBMS Practical: Data Types, Creating Tables, Data Retrieval, and Alter/Drop
Statements
In this practical, we will explore several fundamental SQL operations in a Database
Management System (DBMS). These operations include understanding data types,
creating tables, retrieving data, applying conditional filters, and using the ALTER and
DROP statements to modify or remove table structures.
1. Understanding Data Types in SQL
Data types in SQL define the type of data a column can hold. They play an essential
role in ensuring data integrity by defining constraints on what kind of values can be
stored in each column.
Common SQL Data Types:
 Numeric Data Types:
o INT: Stores whole numbers.
o DECIMAL(p, s): Stores fixed-point numbers, where p is the precision (total
digits) and s is the scale (number of digits after the decimal point).
o FLOAT or REAL: Stores floating-point numbers.
 Character Data Types:
o VARCHAR(n): Variable-length string where n specifies the maximum length.
o CHAR(n): Fixed-length string with a defined length of n.
o TEXT: Stores large text data.
 Date and Time Data Types:
o DATE: Stores the date in YYYY-MM-DD format.
o TIME: Stores time in HH:MM:SS format.
o DATETIME: Stores both date and time.
 Other Data Types:
o BOOLEAN: Stores TRUE or FALSE.
o BLOB or BINARY: Stores binary data like images or files.

2. Creating Tables in SQL


The CREATE TABLE statement is used to define a new table and specify the columns
along with their data types.
Syntax for CREATE TABLE:

7|Page
Example - Creating a Students Table:

This table Students will store information about students, including their ID, name,
birthdate, and grade level.

3. Retrieving Rows using the SELECT Statement


The SELECT statement is used to retrieve data from one or more tables.
Basic SELECT Syntax:

Example - Retrieving All Data from the Students Table:

The * retrieves all columns in the table.


Example - Retrieving Specific Columns:

This retrieves only the FirstName and LastName columns.

4. Conditional Retrieval of Rows using the WHERE Clause


The WHERE clause is used to filter records based on specific conditions.
Basic WHERE Syntax:

Example - Retrieving Students in Grade Level 10:

8|Page
Example - Retrieving Students Born After January 1, 2005:

Example - Using LIKE for Pattern Matching:

Example - Using AND and OR for Multiple Conditions:

5. Altering Tables using the ALTER Statement


The ALTER statement is used to modify the structure of an existing table. You can
add, modify, or drop columns.
Syntax for ALTER TABLE:
 Add a New Column:

 Modify an Existing Column:

 Rename a Column:

 Drop a Column:

Example - Add a Email Column to Students Table:

Example - Drop the Email Column from Students Table:

9|Page
6. Dropping Tables using the DROP Statement
The DROP statement is used to permanently remove a table and all of its data from
the database.
Syntax for DROP TABLE:

Example - Dropping the Students Table:

Be cautious when using DROP because once a table is dropped, all the data is lost
permanently.

7. Practical Exercises
Let's practice some of the SQL commands discussed.
Exercise 1: Create a Books Table
Create a table Books with the following columns:
 BookID (Primary Key, INT)
 Title (VARCHAR)
 Author (VARCHAR)
 PublishDate (DATE)
 Price (DECIMAL(5, 2))

Exercise 2: Insert Data into Books


Insert the following data into the Books table:

10 | P a g e
Exercise 3: Retrieve All Books Published After 2022

Exercise 4: Update Price of a Book


Increase the price of the book with BookID = 1 by 10%.

Exercise 5: Drop the Books Table

11 | P a g e
Task 3: 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.
1. Working with Null Values
In SQL, NULL represents unknown or missing data. To work with NULL values, you need to
use specific operators.
 IS NULL: To check if a value is NULL.
 IS NOT NULL: To check if a value is not NULL.
 COALESCE(): To replace NULL with a specified value.
Example:

2. Matching a Pattern from a Table


You can use the LIKE operator to match a pattern in string columns. It supports wildcards like
% (any number of characters) and _ (exactly one character).
Example:

12 | P a g e
3. Ordering the Result of a Query
To order the results of a query, you use the ORDER BY clause. You can sort results in
ascending (ASC) or descending (DESC) order.
Example:

4. Aggregate Functions
Aggregate functions are used to perform a calculation on a set of values. Common aggregate
functions include COUNT(), SUM(), AVG(), MIN(), and MAX().
Example:

13 | P a g e
5. Grouping the Result of a Query
The GROUP BY clause is used to group rows that have the same values in specified columns.
It is often used with aggregate functions.
Example:

6. Update and Delete Statements


The UPDATE statement is used to modify existing records, and the DELETE statement is used
to remove records from a table.
Example:

14 | P a g e
Putting It All Together
You can combine multiple operations in a single query. For instance, finding the average
salary per department, excluding inactive employees, and ordering the result.
Example:

Summary:
 NULL values: Use IS NULL, IS NOT NULL, and functions like COALESCE().
 Pattern matching: Use LIKE with wildcards (%, _).
 Ordering: Use ORDER BY for sorting results in ascending or descending order.
 Aggregate functions: Use COUNT(), SUM(), AVG(), MIN(), MAX() for summarizing
data.
 Grouping: Use GROUP BY to group data and HAVING to filter groups.
 Update/Delete: Use UPDATE and DELETE to modify or remove data.

15 | P a g e
Task 4: Set Operators, Nested Queries, Joins, Sequences.
1. Set Operators
Set operators combine the results of two or more queries. The main set operators
are:
 UNION: Combines the result of two queries, removing duplicates.
 UNION ALL: Combines the result of two queries, including duplicates.
 INTERSECT: Returns only the common records from two queries.
 EXCEPT (or MINUS in some databases): Returns records from the first query that are
not in the second query.
Example:

 UNION removes duplicates, while UNION ALL does not.


 INTERSECT finds the common data in both queries.
 EXCEPT (or MINUS in some systems like Oracle) finds data in the first query that is
not in the second.

16 | P a g e
2. Nested Queries (Subqueries)
A nested query (or subquery) is a query inside another query. Subqueries can be
used in the SELECT, INSERT, UPDATE, or DELETE statements, or in the WHERE clause.
Types of Nested Queries:
1. Subquery in the SELECT clause: Returns a value for each row.
2. Subquery in the WHERE clause: Used to filter results.
3. Correlated subquery: A subquery that depends on the outer query.
Examples:
 Subquery in the WHERE clause:

 Subquery in the FROM clause:

 Correlated Subquery (where the subquery references a column from the outer
query):

3. Joins
Joins are used to combine data from two or more tables based on a related column.
The most common types of joins are:
 INNER JOIN: Returns records that have matching values in both tables.
 LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table, and
matching records from the right table. If no match, NULL values are returned for
columns from the right table.
 RIGHT JOIN (or RIGHT OUTER JOIN): Similar to LEFT JOIN but returns all records from
the right table.
 FULL OUTER JOIN: Returns records when there is a match in one of the tables.

17 | P a g e
 CROSS JOIN: Returns the Cartesian product of two tables (all combinations of rows).

Examples:
 INNER JOIN:

 LEFT JOIN:

 RIGHT JOIN:

 FULL OUTER JOIN:

 CROSS JOIN:

4. Sequences
A sequence is an object in a DBMS that generates a sequence of unique numbers,
often used for generating primary key values.
Example of Sequence Usage:
 Creating a Sequence:

18 | P a g e
 Using a Sequence to Insert Data:

 Using the Sequence in a Select Query:

 Resetting a Sequence (specific to some DBMS like PostgreSQL or Oracle):

Putting it All Together:


Here's an example that combines a join, subquery, set operator, and sequence.

Summary:
 Set Operators: Combine the results of two queries with UNION, INTERSECT, EXCEPT,
etc.

19 | P a g e
 Nested Queries: Queries inside other queries, useful for filtering, aggregating, or
checking against other datasets.
 Joins: Combine data from multiple tables (e.g., INNER JOIN, LEFT JOIN).
 Sequences: Generate unique values (commonly used for primary keys) with CREATE
SEQUENCE and NEXTVAL.

20 | P a g e
Task 5: Views, Indexes, Database Security and Privileges: Grant and Revoke
Commands, Commit and Rollback Commands.
1. Views:
A view is a virtual table based on the result of a SELECT query. It does not store data
but allows users to interact with the data in a simplified or customized way.
Creating a View:

Example:

Selecting Data from a View:

Dropping a View:

2. Indexes:
An index is used to improve the speed of data retrieval operations on a database
table. It is created on columns that are frequently queried.
Creating an Index:

Example:

Dropping an Index:

3. Database Security and Privileges:

21 | P a g e
In a DBMS, privileges determine the operations that a user can perform on database
objects like tables, views, and stored procedures.

Grant Command:
The GRANT command is used to give privileges to users or roles.

Example:

This grants the user john_doe the ability to SELECT and INSERT data into the
employees table.
Revoke Command:
The REVOKE command removes privileges from users or roles.

Example:

This revokes the INSERT privilege on the employees table from the user john_doe.
4. Commit and Rollback Commands (Transaction Control):
These commands are used to manage transactions in a database, ensuring data
integrity.
COMMIT Command:
The COMMIT command is used to save the changes made during the current
transaction to the database permanently.

Example:

ROLLBACK Command:
The ROLLBACK command is used to undo the changes made in the current
transaction, reverting the database to its state before the transaction began.

22 | P a g e
Example:

Practical Example Workflow:


1. Creating Tables: First, let’s create a sample employees table.

2. Granting Privileges: Grant SELECT and INSERT privileges to a user john_doe.

3. Inserting Data: Insert some records into the employees table

4. Creating a View: Create a view to display employees with salaries greater than
50,000.

5. Using the View: Query data using the view.

6. Creating an Index: Create an index on the emp_salary column to speed up salary-


based queries.

7. Rolling Back a Transaction: Insert a new record and then roll back.

23 | P a g e
8. Committing a Transaction: Insert a new record and commit the changes.

9. Revoking Privileges: Revoke INSERT privilege from john_doe.

Summary of Commands:

Command Description

CREATE VIEW Creates a view based on a SELECT query.

CREATE INDEX Creates an index to speed up query execution.

GRANT Grants specific privileges to a user.

REVOKE Revokes specific privileges from a user.

COMMIT Saves changes made during a transaction.

ROLLBACK Undoes changes made during a transaction.

24 | P a g e
Task 6: PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL Code,
Referencing Non-SQL parameters.
1. PL/SQL Architecture
PL/SQL is a procedural language extension to SQL, designed for seamless integration with
Oracle databases. The architecture of PL/SQL includes the following major components:
a. PL/SQL Engine
The PL/SQL engine is responsible for executing PL/SQL blocks. When a PL/SQL block is
executed, the engine performs various tasks like parsing, optimization, and execution.
b. PL/SQL Block Structure
A PL/SQL block consists of the following sections:
 Declaration Section (optional): This section declares variables, constants, cursors,
and exceptions. It starts with the DECLARE keyword.
 Execution Section: This section contains the executable code that performs the
actual operations (SQL queries, loops, conditional logic, etc.).
 Exception Handling Section (optional): Used to handle exceptions or errors. It starts
with the EXCEPTION keyword.
Example of a basic PL/SQL block:

c. Interaction with SQL


PL/SQL integrates directly with SQL statements. SQL statements can be executed within
PL/SQL blocks for data retrieval, updates, and more.

25 | P a g e
2. Assignments and Expressions in PL/SQL
a. Assignments
In PL/SQL, assignments are made using the := operator. It assigns the value on the right-hand
side to the variable on the left-hand side.
Example of assignment:

b. Expressions
An expression in PL/SQL is any combination of variables, constants, operators, and function
calls that evaluates to a single value.
Example of an expression:

3. Writing PL/SQL Code


a. Variables and Data Types
Variables in PL/SQL are declared in the DECLARE section, and each variable is associated
with a data type (e.g., NUMBER, VARCHAR2, DATE, etc.).
Example of declaring different data types:

26 | P a g e
b. Control Structures
PL/SQL supports control structures like IF...THEN...ELSE, LOOP, and FOR loops.
Example of an IF statement:

c. Cursors
PL/SQL uses cursors to fetch and process rows returned by SQL queries.
Example of an explicit cursor:

4. Referencing Non-SQL Parameters in PL/SQL


Non-SQL parameters are typically used in PL/SQL procedures or functions. These parameters
could be passed to PL/SQL blocks from external sources like applications, triggers, or other
procedures.
a. Passing Parameters to a Procedure
In PL/SQL, you can reference parameters that are passed to a procedure or function.
Parameters can be of the following types:

27 | P a g e
 IN (input): Pass values into the procedure.
 OUT (output): Return values from the procedure.
 IN OUT: Pass and return values.
Example of a procedure with parameters:

b. Referencing Non-SQL Parameters


Non-SQL parameters, such as variables declared in PL/SQL blocks or passed from an external
application, can be referenced directly by their names.
Example of using a non-SQL parameter inside a PL/SQL block:

5. DBMS_OUTPUT in PL/SQL (Practical File)


DBMS_OUTPUT is a built-in package used to display output from PL/SQL blocks.
Example of using DBMS_OUTPUT:

28 | P a g e
This will print "Hello, PL/SQL!" to the output console when executed.
Practical File Structure
A practical file would typically include:
 Problem Statement: Describe the PL/SQL tasks to be performed.
 Code Implementation: Provide PL/SQL code with appropriate comments.
 Execution: Demonstrate how to execute the code and the output.
 Conclusion: Summarize what was learned or achieved.
Example for a simple assignment:
 Problem: Create a PL/SQL block that calculates and prints the bonus of an employee
based on their salary (e.g., 10% of the salary).
 Solution:

29 | P a g e
Task 7: Stored Procedures and Exception Handling.
In a Database Management System (DBMS) practical file, a section on Stored Procedures
and Exception Handling is a crucial part of learning how to create, manage, and handle
errors in the database layer. Below is a detailed overview of the topics with practical
examples that you can include in your practical file.

Stored Procedures
1. What is a Stored Procedure?
A Stored Procedure (SP) is a precompiled collection of one or more SQL statements that can
be executed by the database server. Stored procedures are stored within the database itself
and can be executed multiple times. They help in improving the efficiency of queries and
reducing the number of calls made to the database.
2. Advantages of Stored Procedures:
 Reusability: Can be called multiple times in the application without rewriting the
same code.
 Performance: Precompiled SQL statements improve the speed of execution.
 Security: Restricts direct access to the database.
 Error Handling: Allows centralized error handling logic.
3. Creating a Stored Procedure:
To create a stored procedure, we use the CREATE PROCEDURE statement. Below is an
example:

4. Explanation of the Stored Procedure:


 IN emp_id INT: This is the input parameter which allows the user to pass a value (in
this case, emp_id).
 SELECT * FROM Employees WHERE EmployeeID = emp_id;: This statement retrieves
the employee details based on the provided employee ID.

30 | P a g e
5. Calling a Stored Procedure:

This will execute the GetEmployeeDetails stored procedure and return the result for the employee
with ID 101.

Exception Handling in Stored Procedures

1. What is Exception Handling?

Exception handling in SQL allows us to capture runtime errors (like division by zero, invalid data
types, etc.) and handle them gracefully rather than letting the database process fail or return
incorrect results. In stored procedures, exceptions can be managed with DECLARE, HANDLER,
RESIGNAL, etc.

2. Syntax for Exception Handling:

You can define exception handling in stored procedures using the DECLARE statement to declare
handlers and then respond with an appropriate action like CONTINUE or EXIT.

3. Example of Exception Handling:

Here is an example of how you can use exception handling within a stored procedure in MySQL:

31 | P a g e
4. Explanation of the Example:

 DECLARE EXIT HANDLER FOR SQLEXCEPTION: This part of the code specifies that if any SQL
exception occurs, the handler will be triggered.

 ROLLBACK: In case of an error, this will undo any changes made during the transaction.

 START TRANSACTION and COMMIT: Used to start and commit the transaction.

5. Calling the Stored Procedure with Exception Handling:

Practical Example: Stored Procedure with Exception Handling

Objective:

Write a stored procedure to insert an employee into the Employees table and handle
possible exceptions (e.g., duplicate records, constraint violations).

1. Table Setup:

2. Stored Procedure with Exception Handling:

32 | P a g e
3. Calling the Stored Procedure:

 If the insertion is successful, it will return: Employee inserted successfully!


 If there is an error (e.g., trying to insert duplicate data or violating a constraint), it
will return: Error: Unable to insert employee. Check constraints.

Conclusion:
Stored procedures and exception handling play a crucial role in improving the
performance and reliability of database operations. By storing commonly used
queries and encapsulating them into procedures, you can achieve greater
modularity, security, and better error management. Exception handling ensures that
any errors are caught and dealt with before they can disrupt the entire system.
You can now create this content in your practical file, demonstrating both the
creation and usage of stored procedures, as well as handling exceptions effectively.

33 | P a g e
Task 8: Triggers and Cursor Management in PL/ SQL.
In PL/SQL, Triggers and Cursor Management are key components for automating
database tasks and controlling how data is accessed in your programs.
Here’s a brief overview and practical examples for both, which you can use for your
DBMS practical file:
1. Triggers in PL/SQL
A Trigger is a special type of stored procedure in PL/SQL that is automatically
executed (or "triggered") when certain events occur on a table or view.
Types of Triggers:
 BEFORE Trigger: Executes before an insert, update, or delete operation.
 AFTER Trigger: Executes after an insert, update, or delete operation.
 INSTEAD OF Trigger: Executes in place of an insert, update, or delete operation (used
mainly with views).
Common Uses:
 Enforcing business rules
 Auditing changes
 Data validation
Example: Creating a Trigger
Let's create an AFTER INSERT trigger on an employees table to log any new insert
into a separate auditlog table.
Step 1: Create the tables

Step 2: Create the Trigger

34 | P a g e
Explanation:
 AFTER INSERT ON employees: The trigger fires after an insert is made into the
employees table.
 :NEW.emp_id: Refers to the new value of the emp_id column that was inserted.
 audit_log_seq.NEXTVAL: Assumes you have a sequence for generating unique log_id
values.
Step 3: Testing the Trigger

2. Cursor Management in PL/SQL


A Cursor is a pointer to a context area in memory, used to fetch rows from a SQL
query result. Cursors allow you to process each row individually.
Types of Cursors:
 Implicit Cursor: Automatically created by Oracle for SQL statements like SELECT
INTO, INSERT, UPDATE, DELETE.
 Explicit Cursor: Defined and controlled by the programmer.
Common Uses:
 Fetching and processing rows one by one
 Handling complex queries and result sets
Example: Using an Explicit Cursor
Let's use an explicit cursor to fetch and process employee data from the employees
table.
Step 1: Declare an Explicit Cursor

35 | P a g e
Explanation:
 CURSOR emp_cursor: Declares an explicit cursor to select emp_id, emp_name, and
emp_salary from the employees table.
 FETCH emp_cursor INTO v_emp_id, v_emp_name, v_emp_salary: Fetches one row
at a time into the declared variables.
 EXIT WHEN emp_cursor%NOTFOUND: Exits the loop when there are no more rows
to fetch.
Step 2: Testing the Cursor Code
You can execute the above block in your SQL*Plus or any PL/SQL environment to see
the output using DBMS_OUTPUT.

3. Practical File Format


Part 1: Introduction
 Introduction to Triggers and Cursor Management in PL/SQL.
 Explain their importance and uses in database systems.
Part 2: Trigger Example
 Show the steps for creating and testing the AFTER INSERT trigger.
 Include the code and output.
Part 3: Cursor Example
 Explain the concept of cursors and how to declare an explicit cursor.
 Provide the code for fetching employee data.
 Include a sample output showing how rows are processed one by one.
Part 4: Conclusion
 Summarize the advantages of using triggers and cursors in PL/SQL, such as
automating processes, improving performance, and enforcing data integrity.

36 | P a g e

You might also like