In the area of database management, effective data retrieval is essential particularly when handling large datasets. PostgreSQL offers the functionality of a cursor which allows for incremental data retrieval from extensive result sets.
By using PostgreSQL cursor syntax, developers can manage memory more efficiently and enhance application performance while processing rows one at a time. In this article, We will learn about the Cursor in PostgreSQL by understanding various examples and so on.
What is a Cursor in PostgreSQL?
- A cursor in PostgreSQL is a database object that enables traversal over the result set of a query. It acts as a pointer that allows us to fetch rows sequentially.
- PostgreSQL cursors are particularly useful when working with large tables containing millions of records where traditional SELECT operations may lead to performance issues or even out-of-memory errors.
Syntax of Declaring a Cursor
DECLARE cursor_name CURSOR FOR query;
Explanation:
DECLARE
: The keyword used to declare a cursor.
cursor_name
: The name assigned to the cursor.
query
: The SQL query associated with the cursor
How to Fetch Data from a Cursor?
After declaring a cursor, we can get the data using FETCH. The FETCH gets the next row(s) from the cursor. If no row found, then it returns NULL.
FETCH [direction (rows)] FROM [cursor_name];
Parameters:
'[direction (rows)]'
: Specifies the direction and number of rows to fetch. If no direction is specified, the default is NEXT
.'[cursor_name]'
: The name of the cursor from which to fetch data.
Directions for FETCH
- NEXT: Fetches the next rows.
- PRIOR: Fetches the previous rows.
- FIRST: Fetches the first rows.
- LAST: Fetches the last rows.
- ABSOLUTE count: Fetches the row at the absolute position '
count'
.
- RELATIVE count: Fetches the row at the relative position '
count'
.
- ALL: Fetches all remaining rows.
- FORWARD count: Fetches the next '
count'
rows.
- BACKWARD count: Fetches the previous '
count'
rows.
Steps to Use Cursors in PostgreSQL
Let us take a look at an example of Cursor in PostgreSQL to better understand the concept.
Step 1: Create a Sample Table
Lets, create a sample table using the below commands for examples:
CREATE TABLE students (
student_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
branch_id INT
);
INSERT INTO students (
student_id,
full_name,
branch_id
)
VALUES
(1, 'M.S Dhoni', NULL),
(2, 'Sachin Tendulkar', 1),
(3, 'R. Sharma', 1),
(4, 'S. Raina', 1),
(5, 'B. Kumar', 1),
(6, 'Y. Singh', 2),
(7, 'Virender Sehwag ', 2),
(8, 'Ajinkya Rahane', 2),
(9, 'Shikhar Dhawan', 2),
(10, 'Mohammed Shami', 3),
(11, 'Shreyas Iyer', 3),
(12, 'Mayank Agarwal', 3),
(13, 'K. L. Rahul', 3),
(14, 'Hardik Pandya', 4),
(15, 'Dinesh Karthik', 4),
(16, 'Jasprit Bumrah', 7),
(17, 'Kuldeep Yadav', 7),
(18, 'Yuzvendra Chahal', 8),
(19, 'Rishabh Pant', 8),
(20, 'Sanju Samson', 8)
Step 2: Declare and Use a Cursor
Now that the table is ready we can declare our cursor.
Query:
BEGIN;
DECLARE
my_cursor CURSOR FOR SELECT * FROM students;
Fetch the data.
FETCH 10 FROM my_cursor;
Output:

FETCH PRIOR FROM my_cursor;
FETCH PRIOR FROM my_cursor;
The above query will give you row 9 and 8 since right now our cursor is at 10;
FETCH 6 FROM my_cursor;
Output:

Step 3: Commit the Transaction
Commit the transaction at the end.
COMMIT;
Important Points About Cursor in PostgreSQL
- Cursors must be declared within a transaction block using
BEGIN
and COMMIT
. Outside of a transaction, the cursor's scope is limited to the session.
- By default, cursors in PostgreSQL are scrollable, meaning you can fetch rows in any direction (NEXT, PRIOR, FIRST, LAST). Non-scrollable cursors can only move forward and are declared with '
NO SCROLL
'
.
- PostgreSQL supports different types of cursors like
BINARY
and INSENSITIVE
. The default cursor is INSENSITIVE
, meaning it does not reflect changes made after the cursor is opened.
- Fetching data in smaller chunks (e.g., '
FETCH 100 FROM my_cursor'
) can improve performance by reducing memory consumption and processing time.
Conclusion
Overall, utilizing cursors in PostgreSQL can improve the efficiency of your database interactions. By mastering how to declare a cursor in PostgreSQL and fetch data from a PostgreSQL cursor, you can streamline operations on large tables without compromising system resources. Adopting cursors will enable you to optimize performance and provide a smoother data handling experience in your applications.
Similar Reads
PostgreSQL - INSERT PostgreSQL INSERT statement is one of the fundamental SQL commands used to add new rows to a specified table within a PostgreSQL database. This command allows users to insert data efficiently, whether for a single record or multiple records at once. With the PostgreSQL INSERT INTO clause, we can spe
4 min read
MySQL Cursors A MySQL cursor is a powerful database object designed for retrieving, processing, and managing rows from a result set one at a time. Unlike standard SQL queries that handle sets of rows in bulk, cursors allow for detailed row-by-row operations. In this article, We will learn about MySQL Cursors in d
6 min read
PostgreSQL - Psql commands PostgreSQL, or Postgres, is an object-relational database management system that utilizes the SQL language. PSQL is a powerful interactive terminal for working with the PostgreSQL database. It enables users to execute queries efficiently and manage databases effectively.Here, we highlight some of th
2 min read
PL/SQL Parameterized Cursors PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features. With PL/SQL, you can fetch data from the table, add data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries. PL/SQL contains declaration b
5 min read
PL/SQL Cursor FOR LOOP Oracle PL/SQL is a powerful extension of SQL, specifically designed to provide procedural capabilities for Oracle databases. It allows developers to write complex programs that combine SQL queries with procedural constructs like loops, conditionals, and exception handling. Among these features, PL/S
4 min read
Python PostgreSQL - Limit Clause In this article, we are going to see how to use the limit clause in PostgreSQL using pyscopg2 module in Python. In PostgreSQL LIMIT constraints the number of rows returned by the query. By default, It is used to display some specific number of rows from the top. If we want to skip a number of rows b
2 min read
Python PostgreSQL - Order By In this article, we will discuss how to use order by clause in PostgreSQL using python. The Order By clause is used to sort the records of a table returned by the SELECT clause in ascending order by default, yet asc keyword can be used. If we want to sort the records in descending order then we have
3 min read
Python - Import CSV into PostgreSQL In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example
2 min read
PL/SQL Cursor Update PL/SQL stands for Procedural Language/Structured Query Language. It has block structure programming features. In Oracle PL/SQL, cursors play a vital role in managing and processing query results. Among the various types of cursors, updatable cursors stand out for their ability to fetch data and modi
5 min read
What is Cursor in SQL ? When working with SQL, most operations are performed on entire sets of data. But what if we need to process each row individually maybe to perform some custom logic or apply conditions row-by-row? Cursors come into play in such scenarios, providing a way to process each row individually.Introduction
8 min read