Skip to content
Related Articles

Related Articles

Improve Article

What is Cursor in SQL ?

  • Difficulty Level : Medium
  • Last Updated : 05 Sep, 2019

Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database Server at the Time of Performing DML operations on Table by User. Cursors are used to store Database Tables. There are 2 types of Cursors: Implicit Cursors, and Explicit Cursors. These are explained as following below.

  1. Implicit Cursors:
    Implicit Cursors are also known as Default Cursors of SQL SERVER. These Cursors are allocated by SQL SERVER when the user performs DML operations.
  2. Explicit Cursors :
    Explicit Cursors are Created by Users whenever the user requires them. Explicit Cursors are used for Fetching data from Table in Row-By-Row Manner.

How to create Explicit Cursor:

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

  1. Declare Cursor Object.
    Syntax : DECLARE cursor_name CURSOR FOR SELECT * FROM table_name
    DECLARE s1 CURSOR FOR SELECT * FROM studDetails
  2. Open Cursor Connection.
    Syntax : OPEN cursor_connection



    OPEN s1
  3. Fetch Data from cursor.
    There are total 6 methods to access data from cursor. They are as follows :
    FIRST is used to fetch only the first row from cursor table.
    LAST is used to fetch only last row from cursor table.
    NEXT is used to fetch data in forward direction from cursor table.
    PRIOR is used to fetch data in backward direction from cursor table.
    ABSOLUTE n is used to fetch the exact nth row from cursor table.
    RELATIVE n is used to fetch the data in incremental way as well as decremental way.
    Syntax : FETCH NEXT/FIRST/LAST/PRIOR/ABSOLUTE n/RELATIVE n FROM cursor_name
    FETCH FIRST FROM s1
    FETCH LAST FROM s1
    FETCH NEXT FROM s1
    FETCH PRIOR FROM s1
    FETCH ABSOLUTE 7 FROM s1
    FETCH RELATIVE -2 FROM s1
    
  4. Close cursor connection.
    Syntax : CLOSE cursor_name
    CLOSE s1
  5. Deallocate cursor memory.
    Syntax : DEALLOCATE cursor_name
    DEALLOCATE s1
My Personal Notes arrow_drop_up
Recommended Articles
Page :