A cursor is a placeholder into a selection query that allows you to iterate over subsets of the rows returned by that query.
This document describes cursor usage within SQL transactions. For information about using cursors in PL/pgSQL functions and procedures, see .
Cursors differ from and in that:
- Each cursor is a stateful SQL object that is referred to by a unique name.
- Each cursor requires holding open its own dedicated (read-only) .
- Each cursor operates on a snapshot of the database at the moment that cursor is opened.
Synopsis
Cursors are declared and used with the following keywords:
Examples
These examples assume the presence of the .
Use a cursor
View all open cursors
Known limitations
CockroachDB implements SQL cursor support with the following limitations:
DECLARE only supports forward cursors. Reverse cursors created with DECLARE SCROLL are not supported.
FETCH supports forward, relative, and absolute variants, but only for forward cursors.
BINARY CURSOR, which returns data in the Postgres binary format, is not supported.
WITH HOLD, which allows keeping a cursor open for longer than a transaction by writing its results into a buffer, is accepted as valid syntax within a single transaction but is not supported. It acts as a no-op and does not actually perform the function of WITH HOLD, which is to make the cursor live outside its parent transaction. Instead, if you are using WITH HOLD, you will be forced to close that cursor within the transaction it was created in.
-
This syntax is accepted (but does not have any effect):
-
This syntax is not accepted, and will result in an error:
- Scrollable cursor (also known as reverse
FETCH) is not supported.
- with a cursor is not supported.
- Respect for is not supported. Cursor definitions do not disappear properly if rolled back to a
SAVEPOINT from before they were created.
Differences between cursors and keyset pagination
Cursors are stateful objects that use more database resources than keyset pagination, since each cursor holds open a transaction. However, they are easier to use, and make it easier to get consistent results without having to write complex queries from your application logic. They do not require that the results be returned in a particular order (that is, you don’t have to include an ORDER BY clause), which makes them more flexible.
Keyset pagination queries are usually much faster than cursors since they order by indexed columns. However, in order to get that performance they require that you return results in some defined order that can be calculated by your application’s queries. Because that ordering involves calculating the start/end point of pages of results based on an indexed key, they require more care to write correctly.
See also