SQL Tutorial
SQL Database
SQL Table
SQL Select
SQL Order By
SQL Insert
SQL Update
SQL Delete
Difference
SQL Injection
SQL String Functions
Miscl
- SQL Formatter
- SQL group by
- SQL add/drop/update column operation
- SQL CAST Function
- SQL Comments
- SQL CONCAT Function
- CTE (Common Table Expression)SQL
- How to use distinct in SQL?
- Joining Three or More Tables in SQL
- What is Web SQL?
- How to create functions in SQL?
- How to run SQL Script?
- How to Delete Duplicate Rows in SQL?
- Nth Highest salary
- 12 Codd's Rules
- SQL EXCEPT
- Types of SQL JOIN
- Change datatype of column in SQL
- SQL Auto Increment
- SQL Like
- Commit and Rollback in SQL
- SQL Concatenate
- SQL get month from the date
- Savepoint in SQL
- SQL ORDER BY DATE
- TIME Datatype in SQL
- SQL BETWEEN
- CRUD Operations in SQL
- SQL INDEX
- Scalar Functions in SQL
- SET Operators in SQL
- Types of SQL Commands
- TCL Commands in SQL
- SQL Subquery
- SQL View
- Constraints in SQL
- Pattern Matching in SQL
- SQL Date Functions
- DDL Commands in SQL
- DML Commands in SQL
- SQL CASE
- SQL Inner Join
- SQL IN Operator
- Check Constraint in SQL
- SQL CLAUSES
- SQL LOGICAL OPERATORS
- Delete Column from Table
- Add Column in the Table
- Delete one row in SQL
- Change the Column Value
- How to Add Foreign Key in SQL
- Add a Primary Key
- Insert One or More rows
- How to Use LIKE in SQL
- Cursor in SQL
- Difference Between DROP and Truncate
- SQL Comparison Operators
- SQL COUNT WHERE
- SQL SELECT MIN
- SQL Stored Procedure
- SQL SELECT AVG
- SQL SELECT MAX
- SQL ADD COLUMN
- How to use Auto-Increment in SQL
- SQL Languages
- SQL Arithmetic Operators
- How to Use GROUP BY in SQL
- How to Use ORDER BY in SQL
- Trigger in SQL
- What is Race Condition
- SQL COUNT DISTINCT
PL/SQL Tutorial
Sql Interview Question
SQl Quiz
Cursor in SQL
In SQL, a cursor is a temporary workstation that is allocated by the database server during the execution of a statement.
It is a database object that allows us to access data of one row at a time. This concept of SQL is useful when the user wants to update the rows of the table one by one.
The cursor in SQL is the same as the looping technique of other programming languages. The collection of tuples held by the cursor is known as the active set.
In SQL database systems, users define the cursor using DECLARE statement and take the SELECT statement as the parameter, which helps in returning the set of rows.
In this SQL article, we will learn about the types of a cursor, the life cycle of a cursor, syntax of a cursor, and the implementation of a cursor.
Types of Cursor in SQL
Following are the two types of Cursor in Structured Query Language:
- Implicit Cursor
- Explicit Cursor
Implicit Cursor
These types of cursors are generated and allocated by the SQL server when the system performs INSERT, DELETE, and UPDATE operations on SQL queries.
This cursor is also referred to as the default cursor in SQL.
An implicit cursor is also created by the system when the SELECT query selects the single row.
Explicit Cursor
These types of cursors are created by the user using the SELECT query.
An explicit cursor holds multiple records but processes a single row at a time. It uses the pointer, which moves to another row after reading one row.
It is basically used for gaining extra control over the temporary workstation.
Life Cycle of Cursor
The life cycle of the cursor is described into the following five stages:
- Declare a Cursor
- Open Cursor
- Fetch Data from Cursor
- Close Cursor Connection
- Deallocate cursor
Let's discuss each stage in brief:
1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:
In this syntax, we have to specify the name and data type of the cursor just after the DECLARE keyword. After that, we have to write the SELECT statement, which defines the result set for the cursor.
2. Open Cursor
It is the second stage that opens the cursor for storing the data retrieved from the result set. We can open the cursor by using the following SQL syntax:
3. Fetch Cursor
It is the third stage in the cursor life cycle that fetches the rows for performing the insertion, deletion, and updation operations on the currently active tuple in the cursor.
Following are the six options that are used in syntax for fetching data from the cursor:
i. FIRST: This option allows the system to access only the first record from the cursor table. The syntax for the FIRST option is given below:
ii. LAST: This option allows the system to access only the last record from the cursor table. The syntax for the LAST option is as follows:
iii. NEXT: This method allows the system to access the data in the forward direction from the cursor table. It is the default option. The syntax of this method is as follows:
iv. PRIOR: This method allows the system to access the data in the backward direction from the cursor table. The syntax of this option is as follows:
v. ABSOLUTE n: This method allows the system to access the data of the exact nth row from the cursor table. The syntax of this option is mentioned below:
vi. RELATIVE n: This method allows the system to access the data in both incremental and decremental processes. The syntax of this option is mentioned below:
4. Close Cursor
It is the fourth stage in the process of the cursor. When we complete the work with the cursor, we have to close the cursor in this stage. We can close the cursor in SQL by using the following query:
CLOSE Cursor_Name;
5. Deallocate Cursor
It is the last and fifth stage of the cursor life cycle. In this part, we have to erase the definition of the cursor and discharge all the system resources combined with the cursor.
Syntax of a Cursor in SQL
DECLARE My_Cursor_Name CURSOR // You have to declare the Name of your Cursor
[LOCAL | GLOBAL] // You have to specify the Scope of your Cursor
[FORWARD_ONLY | SCROLL] // You have to specify the movement direction of your Cursor
[ KEYSET | DYNAMIC |STATIC | FAST_FORWARD] // You have to specify the Basic type of your Cursor
[ SCROLL_LOCKS | OPTIMISTIC |READ_ONLY ] // You have to specify the Locks for your Cursor
OPEN My_Cursor_Name // You have to Open Your Cursor
FETCH NEXT FROM My_Cursor_Name // This line fetches the data from your Cursor
CLOSE My_Cursor_Name // Here, you have to close Your Cursor
DEALLOCATE My_Cursor_Name // Here, you have to deallocate the cursor memory.
Basic Type of Cursor
Following are the four basic types of cursor in Structured Query Language:
- STATIC Cursor
- Forward Only cursor
- KEYSET Driven Cursor
- Dynamic Cursor
STATIC Cursor
The static cursor can move in forward as well as backward direction. This type of cursor populates the result set during the creation of a cursor. Compared to other cursors, it is slow and uses more space in the memory.
By default, these types of cursors are scrollable. The static cursor does not allow the database users to modify and delete data.
Forward Only Cursor
This type of cursor accesses and updates the data only in the forward direction through the result set. So, it is the fastest cursor among all the four cursors.
The main disadvantage of this cursor is that it does not support backward scrolling.
Following are the three types of 'Forward only Cursor':
- Forward_Only KEYSET,
- Forward_Only KEYSET,
- FAST_FORWARD
DYNAMIC Cursor
The dynamic cursor is just opposite to the static cursor. It allows us to execute the INSERT, DELETE, and UPDATE operations while the cursor is open.
It checks all the modifications done on the rows and values in the result set.
KEYSET Driven Cursor
This type of cursor accesses the data from the first to the last row and last to the first row. When the user opens the KEYSET cursor, it automatically creates the list of unique values which uniquely identify each row in the entire result set.
Example of Cursor in SQL
Create a Student table in SQL using the following query:
(
Student_RollNo INT PRIMARY KEY,
Student_Name nvarchar(60) NOT NULL,
Student_Course nvarchar(20) NOT NULL,
Student_Age INTNOT NULL,
Student_Marks INT NOT NULL
) ;
Now, insert some values into the above Student table as shown in the following block:
( 2, Rahul, MCA, 21, 98),
( 3, Jones, B.tech, 20, 93),
( 4, Riya, BCA, 19, 89),
( 5, Aaniya, BBA, 21, 92),
( 6, Saket, MCA, 19, 95),
( 7, Shobhit, MBA, 20, 90),
( 8, Ishika, BCA, 21, 89),
( 9, Parul, B.tech, 19, 91),
( 10, Yukti, BCA, 20, 96);
We can check the data of the Student table by using the following SELECT statement in SQL:
This query shows the data of the Student table in the output:
Student_RollNo | Student_Name | Student_Course | Student_Age | Student_Marks |
---|---|---|---|---|
1 | Amit | BCA | 19 | 88 |
2 | Rahul | MCA | 21 | 98 |
3 | Jones | B.tech | 20 | 93 |
4 | Riya | BCA | 19 | 89 |
5 | Aaniya | BBA | 21 | 92 |
6 | Saket | MCA | 19 | 95 |
7 | Shobhit | MBA | 20 | 90 |
8 | Ishika | BCA | 21 | 89 |
9 | Parul | B.tech | 19 | 91 |
10 | Yukti | BCA | 20 | 96 |
Now, we will create the following cursor for displaying the record of students from the Student table:
/* Here, we declare and set counter */
DECLARE @Counter INT
SET @Counter = 1
PRINT '-------- Record of Students --------';
/* Declare the cursor*/
DECLARE Print_Student_Details CURSOR
FOR
SELECT Student_RollNo, Student_Name, Student_Course FROM customer
/* Open the cursor */
OPEN Print_Student_Details
/* Fetch the record from the cursor into the variables. */
FETCH NEXT FROM Print_Student_Details INTO
@Student_RollNo, @Student_Name, @Student_Course
/* LOOP UNTIL RECORDS ARE AVAILABLE. */
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Counter = 1
BEGIN
PRINT 'Student_RollNo' + CHAR(9) + 'Student_Name' + CHAR(9) + CHAR(9) + 'Student_Course'
PRINT '--------------------------'
END
/* This statement prints the current record */
PRINT CAST(@ Student_RollNo AS NVARCHAR(10)) + CHAR(9) + @Student_Name + CHAR(9) + CHAR(9) + @Student_Course
/* This statement increments the counter variable */
SET @Counter = @Counter + 1
/* This statament fetch the next record into the variables. */
FETCH NEXT FROM Print_Student_Details INTO
@Student_RollNo, @Student_Name, @Student_Course
END
/* This statement closes the cursor*/
CLOSE Print_Student_Details
/* This statement deallocates the cursor*/
DEALLOCATE Print_Student_Details
The above cursor gives the following output:
Student_RollNo | Student_Name | Student_Course |
---|---|---|
1 | Amit | BCA |
2 | Rahul | MCA |
3 | Jones | B.tech |
4 | Riya | BCA |
5 | Aaniya | BBA |
6 | Saket | MCA |
7 | Shobhit | MBA |
8 | Ishika | BCA |
9 | Parul | B.tech |
10 | Yukti | BCA |