3
Motivation
A cursor implies iterative processing
a full result set takes too much memory
only some part of the result set is needed, but its size is unknown in advance
it is required to allow the client to control the selection
row-by-row processing is really needed (such cases are quite rare)
We have already learned about the concept of cursors in “Architecture.
A General Overview of PostgreSQL.” In that lecture, cursors were
presented as a server feature, and we explained how to access them using
SQL. Now let’s talk about how to use cursors in the PL/pgSQL language.
Why do we need cursors at all? SQL is a declarative language; first and
foremost, it is designed to work with sets of rows, which is its strength and
advantage. Being a procedural language, PL/pgSQL has to work with data
row by row, using explicit loops. It can be achieved via cursors.
For example, a full SELECT result сan take too much memory, so it has to
be processed piece by piece. Or the size of the result set is unknown in
advance, i.e., it is required to stop the query at some point. Or control over
the query has to be delegated to the client.
(However, we would like to emphasize once again that although such row-
by-row processing may be really required from time to time, the same
outcome can often be achieved using pure SQL; as a result, the code will
become simpler and will work faster.)