DBMS File

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

DATABASE MANAGEMENT SYSTEM

Lab File
[BTCS 505 -18]

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

Chandigarh Group of Colleges - College of Engineering


Landran, Mohali, Punjab – 140307

SUBMITTED TO: SUBMITTED BY:


Harsh Jindal
1914282
5th B1

1
INDEX
S.no Name of Experiment Page no.

1 Introduction to SQL and installation of SQL server/Oracle. 3-9

2 Data Types, Creating Tables, Retrieval of Rows using Select 10-14


Statement, Conditional Retrieval of Rows, Alter and Drop
Statements.

3 Working with Null Values, Matching a Pattern from a Table, 15-19


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. 20-23

5 Views, Indexes, Database Security and Privileges: Grant and 24-26


Revoke Commands, Commit and Rollback Commands.

6 PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL 27-28


Code, Referencing Non-SQL Parameters.

7 Stored Procedures and Exception Handling 29-30

8 Triggers and Cursor Management in PL/SQL. 31-32

2
EXPERIMENT 1
• Aim:Introduction to SQL and installation of SQL server/Oracle.
• Intruduction:SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).It is a standard language
for Relational Database System. It enables a user to create, read, update and delete
relational databases and tables.All the RDBMS like MySQL, Informix, Oracle, MS Access
and SQL Server use SQL as their standard database language.SQL allows users to query
the database in a number of ways, using English-like statements.
• Rules:
1. Structure query language is not case sensitive. Generally, keywords of SQL are written in
uppercase.
2. Statements of SQL are dependent on text lines. We can use a single SQL statement on one
or multiple text line.
3. Using the SQL statements, you can perform most of the actions in a database.
4. SQL depends on tuple relational calculus and relational algebra.
• SQL process:When an SQL command is executing for any RDBMS, then the system
figure out the best way to carry out the request and the SQL engine determines that how to
interpret the task.In the process, various components are included. These components can
be optimization Engine, Query engine, Query dispatcher, classic, etc.All the non-SQL
queries are handled by the classic query engine, but SQL query engine won't handle logical
files.

3
• Installing SQL
1. Firstly you have to search on google SQL server download and click on the very first link
that it shows as shown below. Make sure it is a Microsoft website and not any other third-
party site.

2. Then scroll down and look for Developer edition, click Download Now, and save the file.
The developer edition is a full version and comes packaged with a fully featured free edition
specially designed for developers.

3. Once the download is successful, go to the downloaded folder and look for
the SQLServer2017-SSEI-Dev.exe file. Double click on that file, and you should
see Getting things ready, which means everything is going smoothly.

4
4. After that, it will show you three options Basic, Custom, and Download Media. You need
to select the second option, which is Custom.

5. Then you will be asked where you would like your MS SQL installation files to reside,
choose accordingly, and click on Install. Make sure you have good internet connectivity.
In the meantime, feel free to take a short nap since it will take some time to install.

6. Once the download is complete, you shall see download success. It will take you to the next
steps that are necessary. A new window with the SQL Server Installation Center will open,

5
which will have planning, installation, maintenance, etc. You need to click
on installation and then on the right side of the panel you will find multiple options, you
need to select New SQL Server stand-alone installation or add features to existing
installation.

7. Then it will open the SQL Server 2017 setup window in which, by default, the checkbox
with specify a free edition to Developer would be selected. All you need to do is click next
and accept the license terms and again click on next. It will install the setup files and move
to the next step, which is install rules. You might get a warning of windows firewall, which
you can safely ignore.

6
8. Then you will be directed to the Feature Selection setup in which you will find a lot of
options to select from, like instance features, database engine services, machine learning
services, etc. You need to select the Database engine services and click next.

7
9. In the instance configuration, specify an instance name that will be later used to connect to
the SQL server. Let's name it Datacamp_Sql and click next. You can skip the Server
configuration and directly move on to the database engine configuration.

10. Now you will be in the installation progress mode, wait for a while, and let the installation
complete. Once the installation is complete, you will receive an Installation successful in
the detail box. Feel free to close the SQL server setup window.

• Result: By above experiment student learn to install SQL server.

8
EXPERIMENT 2
• Aim:Data types, Creating Tables, Retrieval of Rows using Select Statement, Conditional
Retrieval of Rows, Alter and Drop Statements.
• Data types:
❖ Introduction: Each column in a database table is required to have a name and a data
type.An SQL developer must decide what type of data that will be stored inside each
column when creating a table. Data types mainly classified into three categories for every
database.
❖ DATA TYPES OF SQL
1. CHAR : This data type is used to store character strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. The maximum number of
characters (i.e. the size) this data type can hold is 255 characters. Syntax is CHAR(SIZE)
Example is CHAR (20)
2. VARCHAR : This data type is used to store variable length alphanumeric data. The
maximum this data type can hold is 2000 characters. One difference between this data type
and the CHAR data type is ORACLE compares VARCHAR values using non-padded
comparison semantics i.e. the inserted values will not be padded with spaces. Syntax is
VARCHAR(SIZE)
Example is VARCHAR (20) OR VARCHAR2 (20)
3. NUMBER : The NUMBER data type is used to store numbers (fixed or floating point).
Numbers of virtually any magnitude maybe stored up to 38 digits of precision. Numbers as
large as 9.99 * 10 to the power of 124, i.e. followed by 125 zeros can be stored. The
precision, (P), determines the maximum length of the data, whereas the scale, (S),
determines the number of places to the right of the decimal. If scale is omitted then the
default is zero. If precision is omitted values are stored with their original precision up to
the maximum of 38 digits.
Syntax is NUMBER (P, S) Example is NUMBER (10, 2)
4. LONG :This data type is used to store variable length character strings containing up to
2GB. LONG data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot be applied
to LONG values.
Syntax is LONG (SIZE) Example is LONG (20)

9
5. DATE :This data type is used to represent data and time. The standard format id DD-MM-
YY as in 13-JUL-85. To enter dates other than the standard format, use the appropriate
functions. Date Time stores date in the 24-hour format. By default, the time in a date field
is 12:00:00 am, if no time portion is specified. The default date for a date field is the first
day of the current month. Syntax is DATE
6. LONG RAW : LONG RAW data types are used to store binary data, such as Digitized
picture or image. Data loaded into columns of these data types are stored without any
further conversion. LONG RAW data type can contain up to 2GB. Values stored in
columns having LONG RAW data type cannot be indexed. Syntax is LONGRAW (SIZE)
7. RAW : It is used to hold strings of byte oriented data. Data type can have a maximum
length of 255 bytes. Syntax is RAW(SIZE).
• Creating Tables:A table is basic unit of storage. It is composed of rows and columns. To
create a table we will name the table and the columns of the table. We follow the rules to
name tables and columns:-
It must begin with a letter and can be up to 30 characters long.
It must not be duplicate and not any reserved word.
SYNTAX to create a table is
CREATE TABLE tablename (column_name1 datatype (size), column_name2 datatype (size)
…);
Example is CREATE TABLE student (rollno number (4), name varchar2 (15));
• Creating table in SQL:

10
• Retrieval of Rows using Select Statement:
SELECTING ALL COLUMNS OF THE TABLE:A ‘SELECT’ statement is used as a
DATA RETRIVAL statement i.e. It retrieves information from the database.
SYNTAX:
SQL> SELECT * FROM TABLE NAME;
SELECT identifies WHAT COLUMNS.
FROM identifies WHICH TABLE.

SELECTING SPECIFIC COLUMNS OF THE TABLE:


SYNTAX:
SQL> SELECT ENAME,JOB FROM EMP;
We can use SELECT statement to display specific columns of the table by specifying the
column names separated by commas. As shown above
In SELECT clause We specify the column names, in the order in which we want them to appear
as output.

11
• Conditional Retrieval of Rows:
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SYNTAX
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN
If you know the exact value you want to return for at least one of the columns

• Alter: After creating a table one may have need to change the table either by add new
columns or by modify existing columns. One can do so by using alter table command.
SYNTAX ALTER TABLE tablename ADD(col1 datatype,col2 datatype);
SYNTAX to modify a column is
ALTER TABLE tablename MODIFY(col1 datatype,col2 datatype);

12
• DROP TABLE:The DROP TABLE statement is used to drop an existing table in a
database.
SYNTAX
DROP TABLE tablename

• Result:Through above experiment student about Data types, how to Create Tables,
Retrieval of Rows using Select Statement, Conditional Retrieval of Rows, Alter and Drop
Statements.

13
EXPERIMENT 3
• Aim: 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.
• Working with null values:
• Introduction: A field with a NULL value is a field with no value.If a field in a table is
optional, it is possible to insert a new record or update a record without adding a value to
this field. Then, the field will be saved with a NULL value.A NULL value is different from
a zero value or a field that contains spaces. A field with a NULL value is one that has been
left blank during record creation.
• Imlementation:

• Matching a Pattern from a Table


• Introduction: SQL has a standard pattern matching technique using the 'LIKE' operator.
But, it also supports the regular expression pattern matching for better functionality.
• Implementation:print student name whose city name ends with ‘a’.

14
• Ordering the Result of a Query: Whenever we want to sort the records based on the
columns stored in the tables of the SQL database, then we consider using the ORDER BY
clause in SQL.The ORDER BY clause in SQL will help us to sort the records based on the
specific column of a table.

• SQL Aggregate Functions:SQL aggregation function is used to perform the calculations


on multiple rows of a single column of a table. It returns a single value.It is also used to
summarize the data.
1. COUNT FUNCTION:COUNT function is used to Count the number of rows in a database
table.
Synatx:SELECT COUNT(column_name) FROM table_name WHERE condition;

15
2. Average function:The AVG() function returns the average value of a numeric column.
SELECT AVG(column_name) FROM table_name ;

3. Sum function:The SUM() function returns the total sum of a numeric column.
Syntax:SELECT SUM(column_name) FROM table_name ;

4. Min function:The MIN() function returns the smallest value of the selected column.

16
5. Max function:The MAX() function returns the largest value of the selected column.

• Grouping the Result of a Query: In SQL, The Group By statement is used for organizing
similar data into groups. The data is further organized with the help of equivalent function.
SYNTAX :
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE
column_name operator value GROUP BY column_name

17
• Update and Delete Statements: The UPDATE statement is used to modify the existing
records in a table.
SYNTAX:
SQL> UPDATE cse SET rollno=21 WHERE student='ITIKA';.

• Delete: The DELETE statement is used to delete existing records in a table.


SYNTAX:
SQL> DELETE from CSE where rollno BETWEEN 605 AND 630;
i.e. DELETE FROM table [WHERE condition];

• Result:By above experiment student learn about various DML commands in SQL.

18
EXPERIMENT 4
• Aim: Set Operators, Nested Queries, Joins, Sequences.
• Introduction:
1. The union clause: merges the outputs of multiple queries into a single set of rows and
columns. It combines rows returned by two select statements by eliminating duplicate rows.
SYNTAX :SQL>SELECT UNION SELECT ;
2. UNION ALL:UNION and UNION ALL are similar in their functioning with a slight
difference. But UNION ALL gives the result set without removing duplication and sorting
the data.

3. INTERSECT:The intersect operator combines two select statements and return only those
rows that are returned by both queries.
SYNTAX:SQL>SELECT INTERSECT SELECT ;

4. MINUS:It combines the result of two queries and returns only those values that are selected
by first query but not in second query.

19
SYNTAX :SQL>SELECT MINUS SELECT ;

• Nested Queries: A sub query is a form of an SQL statement that appears inside another
SQL statement. It is also termed as nested query. The statement containing a sub query is
called a parent statement. The parent statement uses the rows returned by the sub query. It
can be used by the following commands:
1. To insert records in a target table.
2. To create tables and insert records in the table created.
3. To update records in a target table.
4. To create views.
5. To provide values for conditions in WHERE, HAVING, IN etc. used with SELECT,
UPDATE, and DELETE statements.
TYPES OF SUB QUERIES
• SINGLE ROW
It returns one row from inner nested query.
EXAMPLE IS: SQL>SELECT deptno FROM emp WHERE ename =’MILLER’;
• MULTIPLE ROW
Subqueries that return more than one row called multiple row queries. Operators like
IN,ALL,ANY are used.
EXAMPLESQL>SELECT ename,sal,deptno FROM emp WHERE sal IN (SELECT min(sal)
FROM emp GROUP BY deptno);

20
• JOINS:A JOIN can be recognized in sql select statement if its has more than one table after
from keyword. This join condition is based on primary keys and foreign keys. There must
be n-1 join conditions for n joins to tables. If join condition is omitted then the result is
Cartesian product.
SYNTAX
SQL>SELECT “list of columns” FROM table1, table2 WHERE “condition”;
TYPES OF JOINS
1. EQUI JOIN : It returns all rows from tables where there is a match. Tables are joined on
columns that have the same datatype & size in table. It is also known as equality join or
simple join or inner join.
SYNTAX:
SELECTfield1,field2 FROM table1,table2 WHERE table1.field=table2.field;
2. CARTESION JOIN : When the join condition is omitted the result is Cartesian join of
two or more tables in which all the combinations of rows will be displayed. All the rows
are joined to all rows of the second table.
SYNTAX
SQL>SELECT field1, field2 FROM table1, table2;
EXAMPLE
SQL>SELECT ename, dname FROM emp, dept;
3. OUTER JOIN : While using equi join we see that if there exists certain rows in one table
which don’t have corresponding values in the second table thn those rows will not be
selected. We can forcefully select those rows by outer join. The rows for those columns
will have NULL values.

21
SYNTAX
SELECT table1.col, table2.col FROM table1, table2 WHERE table1.col (+) = table2.col;
EXAMPLE
SQL>SELECT empno, ename, emp.deptno, dname FROM emp, dept WHERE emp.deptno (+)
= dept.deptno;
4. SELF JOIN : The self join can be seen as join of two copies of the same table. The table
is not actually copied but sql performs the command as though it were.
EXAMPLE
SQL>SELECT e.ename, m.ename FROM emp e, emp m WHERE e.mgr=e.empno;
• Sequence :is a set of integers 1, 2, 3, … that are generated and supported by some database
systems to produce unique values on demand.
A sequence is a user defined schema bound object that generates a sequence of numeric
values.Sequences are frequently used in many databases because many applications require
each row in a table to contain a unique value and sequences provides an easy way to
generate them.

22
EXPERIMENT 5

• Aim:Views, Indexes, Database Security and Privileges: Grant and Revoke Commands,
Commit and Rollback Commands.

• VIEWS :A view is very commonly used database object that is derived at runtime. A view

contains data of its own. Its contents are derived from another table. The command for
creating view is CREATE VIEW command. Editing in the tables are automatically
reflected in the views. It is virtual table & does not have any data of its own.
SYNTAX TO CREATE A VIEW IS:
SQL>CREATE [OR REPLACE] VIEW view name AS sub query
EXAMPLE IS: SQL>CREATE VIEW monika AS SELECT empno, ename, sal, comm
FROM emp;
• TYPES OF VIEWS
1. JOIN VIEW :It is defined as view that has more than one table specified in from clause
and does not contain following clauses i.e. distinct, aggregation, group by. This type of
view allows update, insert and delete command to change data in table.
SYNTAX SQL>CREATE OR REPLACE VIEW monika AS SELECT ename, empno, sal
FROM emp, dept WHERE emp.deptno = dept.deptno;
2. INLINE VIEW:Oracle also offers an inline view that is very handy and inline view is part
of SQL statements. It allows you in body of SQL statement to define SQL for view that
SQL statement will use to resolve its query.
3. MATERIALIZED VIEW:Snapshot also called materialized view. It is defined as copy
of part of table or entire table. It reflects the current status of table that is being copied. The
original status table is also called master table. Two types are Read only and update. Read-
only does not allow changes to be made in view

23
• Indexes:An index can be created in a table to find data more quickly and efficiently the
users cannot see the indexes, they are just used to speed up searches/queries.
Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name ON table_name (column_name)

• Grant: It is used to give user access privileges to a database.


Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

• Revoke: It is used to take back permissions from the user.


Example
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
Commit Command : Commit in SQL is a transaction control language which is used to
permanently save the changes done in the transaction in tables/databases.
SYNTAX :
COMMIT;

24
Rollback Command : Rollback in SQL is a transactional control language which is used
to undo the transactions that have not been saved in database.
SYNTAX :
ROLLBACK;

25
EXPERIMENT NO. – 6

AIM : PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL Code,


Referencing Non-SQL parameters.

PL/SQL Architecture : PL/SQL stands for Procedural Language/Structured Query


Language. The PL/SQL is a case insensitive, a robust procedural extension of the SQL.
PL/SQL was developed by Oracle Corporation within the early ’90s to reinforce the capabilities
of SQL. PL/SQL architecture defines how the PL/SQL blocks are executed in Oracle. Oracle
provides PL/SQL engine that executes the Procedural Language part of a block. When an
application program or a user invokes a PL/SQL block, it is submitted to the PL/SQL engine
available locally. PL/SQL engine extracts the Procedural Language statements of the block.
These statements are then executed separately by the PL/SQL processor. The SQL statements
in the block are passed to the SQL processor of Oracle server. These are separately executed.

Assignments and Expressions : The assignment statement sets a previously-declared


variable or formal OUT or IN OUT parameter to the value of an expression.
SYNTAX :
Variable := Expression

Variable specifies an identifier for a previously-declared variable, OUT formal parameter, or


IN OUT formal parameter.
Expression specifies an expression that evaluates to a single value. The data type of this value
must be compatible with the data type of variable.
Writing PL/SQL Code : PL/SQL is a block structured language with procedural
techniques with features like logic building, looping, error-handling mechanisms, data-types,
variables, subroutines, procedural constructs. PL/SQL block consists of:
DECLARE
- used to declare variables and constants

26
- is an optional section
- is also used to declare type declarations, PL/SQL procedures and functions, which are local
to module
BEGIN
- is the executable section containing the code, which is executed when block is run
- is compulsory
EXCEPTION
- handles exceptions occurring during processing
- used to place predefined error-handlers or user-defined exceptions
- code contained in this section is executed only when an error occurs
- is an optional section
End;
STRUCTURE OF PL/SQL : PL SQL is structured in logical blocks of code. Each block has
multiple subsections.
[DECLARE]
<declaration statements>;
[BEGIN]
<Execution statements>;
[EXCEPTION]
<Exception statements>;
END;

27
EXPERIMENT NO. – 7

AIM : Stored Procedures and Exception Handling.


Stored Procedures : A stored procedure is a named PL/SQL code block that has compiled
and stored in oracle engine. The stored procedure are called by any PL/SQL block that appears
within an application before the procedure is stored the oracle engine compiled it.
SYNTAX :
CREATE OR REPLACE PROCEDURE procedurename
[local declaration];
BEGIN
PL/SQL subprogram body;
[EXCEPTION
exception pl/sql block;]
END;

Stored procedure for Adding Two Numbers -

Exception Handling : An exception is an error which disrupts the normal flow of program
instructions. Exceptions will stop the program from executing further, so to avoid such
condition, they need to be captured and handled separately. This process is called as Exception-
Handling, in which the programmer handles the exception that can occur at the run time.
PL/SQL provides the exception block which raises the exception thus helping the programmer
to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL –
• System defined Exception
• User defined Exceptions
SYSTEM DEFINED EXCEPTION : These exceptions are predefined in PL/SQL which get
raised WHEN certain database rule is violated. These exceptions have a unique exception name
and error number. These exceptions are already defined in the ‘STANDARD’ package in
Oracle. Some System Defined Exceptions are -
Exception Error Code Raised if

28
CURSOR_ALREADY_OPEN ORA-06511 An attempt is made to OPEN an already
open cursor. A cursor must be CLOSE
before it can be reopen it.
DUP_VAL_ON_INDEX ORA-00001 Attempt is made to insert to update
duplicate values in UNIQUE database
columns.
TOO_MANY_ROWS ORA-01422 A SELECT INTO returns more than
one row.
ZREO_DIVIDE ORA-01476 An attempt is made to divide a number
by zero.
NO_DATA_FOUND ORA-01403 A SELECT INTO returns no rows, or
you refer to an uninitialized row in a
Pl/SQL table.
INVALID_CURSOR ORA-01001 An illegal cursor operation such as
closing an unopened cursor.
NOT_LOGGED_ON ORA-01012 PL/SQL program issues a database calls
without being logged on to Oracle.

SYNTAX :
BEGIN
<execution block>
EXCEPTION
WHEN <exceptionl_name>
THEN
<Exception handling code for the “exception 1 _name’' >
WHEN OTHERS
THEN
<Default exception handling code for all exceptions >
END;
USER DEFINED EXCEPTION : The users can create their own exceptions according to the
need and to raise these exceptions explicitly raise command is used. The exception that is
defined in the package specification is public exception, and it is visible wherever the package
is accessible.
SYNTAX :
DECLARE
<exception_name> EXCEPTION;
BEGIN
<Execution block>
RAISE <exception_name>
EXCEPTION
WHEN <exception_name> THEN
<Handler>END

29
EXPERIMENT NO. – 8

AIM : Triggers and Cursor Management in PL/SQL.


Triggers : Triggers are stored programs that are fired by Oracle engine automatically when
DML Statements like insert, update, delete are executed on the table or some events occur.
Parts of a Trigger are –
• Triggering event or statement
• Triggering restriction or constraint
• Trigger action
TRIGGERING EVENT OR STATEMENT : It is an SQL statement that causes a trigger to
be fired. It can be an insert, delete or update statement for a specific table.
TRIGGERING RESTRICTION OR CONSTRAINT : It specifies a boolean expression that
must be true for the triggered to be fired. A trigger restriction is specified using 'WHEN'
CLAUSE.
TRIGGER ACTION : A trigger action is the PL/SQL code to be executed when a triggering
statement is encountered and the trigger restriction evaluates to true. The PL/SQL block can
contain SQL and PL/SQL statement and can further call procedures and functions.
SYNTAX :
CREATE OR REPLACE TRIGGER[unserscheme] triggername
{BEFORE,AFTER,INSTEAD OF}
[DELEATE,INSERT,UPDATE[OF column name,......]}
ON[userschema.]tablename
REFERENCING{OLD AS old NEW AS new}}
FOR EACH ROW[WHEN condition]]
DECLARE
Declaration of variables;
declaration of constants;
BEGIN
PL/SQL Executable;
EXCEPTION
Exception PL/SQL block;
END;
Trigger is stored into database and invoked repeatedly, when specific condition match.
Cursor Management : A Cursor is a private SQL work area that Oracle uses to execute
SQL statements and store information. A cursor is a pointer that points to a result of a query.
The data that is stored in the cursor is called the Active Data Set. Conceptually the size of
cursor in memory is the size required to hold the number of rows in Active Data Set. The actual
size ,however, is determined by the Oracle engine’s built in memory management capabilities
and the amount of memory available. Oracle has a predefined area in main memory set aside,

30
within which cursors are opened. Hence the cursor’s size will be limited by the size of this
predefined area.
There are two types of Cursors in PL/SQL -
• Implicit Cursor
• Explicit Cursor
IMPLICIT CURSOR : If the Oracle engine opened a cursor for its internal processing it is
known as an Implicit Cursor. It is created automatically for the user by Oracle when a query is
executed and is simpler to code.
SYNTAX :
CURSOR cursor_name IS select_statement;
EXPLICIT CURSOR : Explicit Cursors are declared explicitly by the user, along with other
identifiers to be used in a PL/SQL block. These are also known as user-defined cursors, defined
in the DECLARE section of the PL/SQL block.
SYNTAX :
CURSOR cursor_name IS select_statement;
DECLARE variables;
records;
Create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;

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.
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.

31

You might also like