EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial Cursors in PostgreSQL
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

Cursors in PostgreSQL

By Priya PedamkarPriya Pedamkar

Cursors in PostgreSQL

Introduction to cursors in PostgreSQL

A cursor is very important in PostgreSQL, using a cursor in PostgreSQL, it is possible to encapsulate the query instead of executing a whole query at once; after encapsulating query, it is possible to read few rows from the result set, the main purpose of doing this is to avoid memory consumption of database server if the result of the query contains more rows, for-loop automatically use the cursor to avoid memory issue in PostgreSQL, this is automatically done by for loop in PostgreSQL, most important use of cursor is it will read result few rows at one time.

Syntax 

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Below is the syntax.

Create or replace function (function name)
Return text (return value) as $$
DECLARE cursor_name (Any name given to cursor) [BINARY] [ INSENSITIVE ] [ SCROLL ] CURSOR (keyword) for query (query to use in cursor)
[ for { READ ONLY (defines cursor only for read only) | UPDATE [ OF column ]}] Begin
Open cursor cursor_name
FETCH (KEYWORD) [ FORWARD | BACKWARD ] (specify the direction)
[ # | ALL | NEXT | PRIOR (Specify the direction) ] [ IN | FROM ] CURSOR (cursor name)
Close cursor_name
Return
END $$
Language pl/pgsql

Below is the parameter description of the above syntax are as follows.

  • Declare – Declare keyword to declare a cursor in PostgreSQL.
  • Cursor name – Any name given to the cursor to declare a cursor.
  • Binary – This is an optional cursor it fetches output in ASCII format. It is only efficient for custom applications.
  • Insensitive – Keyword that describes the default behaviour. Insensitive keyword defines that data was never changed from other connections in PostgreSQL cursor.
  • Scroll – Scroll keyword also describes the default behaviour of PostgreSQL. The scroll is defined as that cursor can select multiple rows at one time.
  • The cursor for – It is used to describe the complete query result set.
  • Query – Actual query used in declare cursor to retrieve result set data.
  • Read-only – Read the only keyword is defined as the cursor is only for read-only.
  • Fetch – Use the fetch command to retrieve rows.
  • Forward – Specify the direction; in PostgreSQL, forward is used as default.
  • Backwards – Specify the direction.
  • Next – The next keyword returns the next cursor row from the current cursor position.
  • Prior – This keyword causes a single row preceding the current cursor position.
  • Create or replace function – Create a function to create a new function.
  • Declare – Variable to declare a cursor in PostgreSQL.
  • Begin – Begin keyword.
  • Open – Open the keyword to open the cursor.
  • Close – Close the keyword to close the cursor.
  • Language – Language used to create a function to describe cursor in PostgreSQL.

Cursors actions in PostgreSQL

We are using employee and customer tables to describe examples.

Code:

CREATE TABLE Employee ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), PRIMARY KEY (emp_name));
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (1, 'ABC', 'Pune', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (1, 'PQR', 'Pune', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (1, 'XYZ', 'Mumbai', '1234567890');

Cursors in PostgreSQL output 1

\d+ employee;

Cursors in PostgreSQL output 2

\d+ customer;

Cursors in PostgreSQL output 2.2

Example of employee and customer table to describe cursor

Below is the action of the cursor are as follows.

  • Declare
  • Open
  • Fetch
  • Close

1. Declare

Below is the syntax of declare cursor in PostgreSQL. In the below example, test_cur is declared to hold all records from the employee table.

Syntax 

Below is the example of declaring:

DECLARE cursor_name (Any name given to cursor) [BINARY] [INSENSITIVE] [SCROLL] CURSOR (keyword) for query (query to use in cursor)
[For {READ ONLY | UPDATE [OF column (defines cursor only for read only)]}]

Example 

Below is the example of declaring cursor in PostgreSQL.

BEGIN;
DECLARE test_cur CURSOR WITH HOLD FOR SELECT * FROM Employee ORDER BY emp_id;
COMMIT;

output 3

2. Open

The open keyword is used to open a cursor in PostgreSQL. Below is the example

Syntax 

Open [[ NO ] SCROLL } FOR query (any query);

Example 

Open test_cursor for select * from employee where emp_id = 1;

3. Fetch

Below is the syntax and example:

Syntax

FETCH [direction {FROM | IN}] cursor_name into target;

Example 

fetch 1 from test_cur;

Cursors in PostgreSQL output 4

fetch 2 from test_cur;

Cursors in PostgreSQL output 4.2

4. Close

Below is the syntax and example:

Syntax 

Close cursor_name;

Example 

close test_cur;

output 5

Close the cursor.

Example of the cursor in PostgreSQL

  • Below is the example of creating a cursor using the function in PostgreSQL.
  • We have used the employee and customer table to join the table.

Example 

CREATE OR REPLACE FUNCTION testing_trigger()
RETURNS SETOF varchar AS
$cursor_test$
DECLARE
cur CURSOR FOR select * from employee emp
left join customer cust on emp.emp_id = cust.cust_id;
test_cur RECORD;
BEGIN
open cur;
LOOP
fetch cur into test_cur;
exit when test_cur = null;
if test_cur.customer like '%AB%' then
return next test_cur.customer;
end if;
END LOOP;
close cur;
END;
$cursor_test$
LANGUAGE plpgsql VOLATILE;

output 6

Importance of cursors in PostgreSQL

Below is the importance are as follows.

  • The main importance of the cursor in PostgreSQL retrieves a single record from the result set.
  • This cursor will save time because we don’t need to wait for retrieving or processing the whole set of data.
  • This cursor saves memory because the client and server did not need more memory to store the data results.
  • The cursor minimizes the load on the server as well as our network bandwidth.
  • If we are doing operations on the table, it will not affect the cursor directly. While we are holding a row, other processes can update, select or delete the rows.

Conclusion

It is essential in PostgreSQL to fetch single records from the whole result set. It is used to saves memory and network bandwidth on the server.

If we are reading data from the cursor, other sessions can do their operations; there is no impact on other connections.

Recommended Articles

This is a guide to Cursors in PostgreSQL. Here we discuss the Cursor’s actions along with the examples and importance. You may also have a look at the following articles to learn more –

  1. What is PostgreSQL?
  2. PostgreSQL String Functions
  3. PostgreSQL Operators
  4. How to Modify PostgreSQL Views?
  5. Guide to PostgreSQL FETCH
  6. Guide to Python Return Value
  7. PostgreSQL COMMIT | Examples
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more