DECLARE(7)
๐ฆ DECLARE ๐ฆ
okay so bestie, this is the DECLARE(7) page from the PostgreSQL 16.15 docs โ the one thatโs literally all about defining a cursor. yes, that DECLARE. itโs giving โsmall rows at a time out of a bigger queryโ main character energy, and weโre gonna get into it. ๐
๐ธ NAME ๐ธ
DECLARE โ define a cursor. thatโs the whole vibe: you name a cursor so you can pull a few rows at a time out of a larger query. periodt.
โจ SYNOPSIS โจ
DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
CURSOR [ { WITH | WITHOUT } HOLD ] FOR query
๐ DESCRIPTION ๐
DECLARE lets a user create cursors, which can be used to retrieve a small number of rows at a time out of a larger query. after the cursor is created, rows are fetched from it using FETCH.
Note: this page describes usage of cursors at the SQL command level. if youโre trying to use cursors inside a PL/pgSQL function, the rules are different โ see Section 43.7.
๐ PARAMETERS ๐
nameโ the name of the cursor to be created. this must be different from any other active cursor name in the session.BINARYโ causes the cursor to return data in binary rather than in text format.ASENSITIVE,INSENSITIVEโ cursor sensitivity determines whether changes to the data underlying the cursor, done in the same transaction, after the cursor has been declared, are visible in the cursor.INSENSITIVEmeans they are not visible,ASENSITIVEmeans the behavior is implementation-dependent. a third behavior,SENSITIVE, meaning that such changes are visible in the cursor, is not available in PostgreSQL. in PostgreSQL, all cursors are insensitive; so these key words have no effect and are only accepted for compatibility with the SQL standard.
specifying INSENSITIVE together with FOR UPDATE or FOR SHARE is an error. ๐จ
SCROLL,NO SCROLLโSCROLLspecifies that the cursor can be used to retrieve rows in a nonsequential fashion (e.g., backward). depending upon the complexity of the queryโs execution plan, specifyingSCROLLmight impose a performance penalty on the queryโs execution time.NO SCROLLspecifies that the cursor cannot be used to retrieve rows in a nonsequential fashion. the default is to allow scrolling in some cases; this is not the same as specifyingSCROLL. see Notes below for details.WITH HOLD,WITHOUT HOLDโWITH HOLDspecifies that the cursor can continue to be used after the transaction that created it successfully commits.WITHOUT HOLDspecifies that the cursor cannot be used outside of the transaction that created it. if neitherWITHOUT HOLDnorWITH HOLDis specified,WITHOUT HOLDis the default.queryโ aSELECTorVALUEScommand which will provide the rows to be returned by the cursor.
the key words ASENSITIVE, BINARY, INSENSITIVE, and SCROLL can appear in any order.
๐ฅ NOTES ๐ฅ
normal cursors return data in text format, the same as a SELECT would produce. the BINARY option specifies that the cursor should return data in binary format. this reduces conversion effort for both the server and client, at the cost of more programmer effort to deal with platform-dependent binary data formats. as an example, if a query returns a value of one from an integer column, you would get a string of 1 with a default cursor, whereas with a binary cursor you would get a 4-byte field containing the internal representation of the value (in big-endian byte order).
binary cursors should be used carefully. many applications, including psql, are not prepared to handle binary cursors and expect data to come back in the text format. ๐ญ
Note: when the client application uses the โextended queryโ protocol to issue aFETCHcommand, theBindprotocol message specifies whether data is to be retrieved in text or binary format. this choice overrides the way that the cursor is defined. the concept of a binary cursor as such is thus obsolete when using extended query protocol โ any cursor can be treated as either text or binary.
unless WITH HOLD is specified, the cursor created by this command can only be used within the current transaction. thus, DECLARE without WITH HOLD is useless outside a transaction block: the cursor would survive only to the completion of the statement. therefore PostgreSQL reports an error if such a command is used outside a transaction block. use BEGIN and COMMIT (or ROLLBACK) to define a transaction block.
if WITH HOLD is specified and the transaction that created the cursor successfully commits, the cursor can continue to be accessed by subsequent transactions in the same session. (but if the creating transaction is aborted, the cursor is removed.) a cursor created with WITH HOLD is closed when an explicit CLOSE command is issued on it, or the session ends. in the current implementation, the rows represented by a held cursor are copied into a temporary file or memory area so that they remain available for subsequent transactions.
WITH HOLD may not be specified when the query includes FOR UPDATE or FOR SHARE.
the SCROLL option should be specified when defining a cursor that will be used to fetch backwards. this is required by the SQL standard. however, for compatibility with earlier versions, PostgreSQL will allow backward fetches without SCROLL, if the cursorโs query plan is simple enough that no extra overhead is needed to support it. however, application developers are advised not to rely on using backward fetches from a cursor that has not been created with SCROLL. if NO SCROLL is specified, then backward fetches are disallowed in any case.
backward fetches are also disallowed when the query includes FOR UPDATE or FOR SHARE; therefore SCROLL may not be specified in this case.
Caution: scrollable cursors may give unexpected results if they invoke any volatile functions (see Section 38.7). when a previously fetched row is re-fetched, the functions might be re-executed, perhaps leading to results different from the first time. itโs best to specifyNO SCROLLfor a query involving volatile functions. if that is not practical, one workaround is to declare the cursorSCROLL WITH HOLDand commit the transaction before reading any rows from it. this will force the entire output of the cursor to be materialized in temporary storage, so that volatile functions are executed exactly once for each row.
if the cursorโs query includes FOR UPDATE or FOR SHARE, then returned rows are locked at the time they are first fetched, in the same way as for a regular SELECT command with these options. in addition, the returned rows will be the most up-to-date versions.
Caution: it is generally recommended to useFOR UPDATEif the cursor is intended to be used withUPDATE ... WHERE CURRENT OForDELETE ... WHERE CURRENT OF. usingFOR UPDATEprevents other sessions from changing the rows between the time they are fetched and the time they are updated. withoutFOR UPDATE, a subsequentWHERE CURRENT OFcommand will have no effect if the row was changed since the cursor was created. another reason to useFOR UPDATEis that without it, a subsequentWHERE CURRENT OFmight fail if the cursor query does not meet the SQL standardโs rules for being โsimply updatableโ (in particular, the cursor must reference just one table and not use grouping orORDER BY). cursors that are not simply updatable might work, or might not, depending on plan choice details; so in the worst case, an application might work in testing and then fail in production. ifFOR UPDATEis specified, the cursor is guaranteed to be updatable. the main reason not to useFOR UPDATEwithWHERE CURRENT OFis if you need the cursor to be scrollable, or to be isolated from concurrent updates (that is, continue to show the old data). if this is a requirement, pay close heed to the caveats shown above. ๐
the SQL standard only makes provisions for cursors in embedded SQL. the PostgreSQL server does not implement an OPEN statement for cursors; a cursor is considered to be open when it is declared. however, ECPG, the embedded SQL preprocessor for PostgreSQL, supports the standard SQL cursor conventions, including those involving DECLARE and OPEN statements.
the server data structure underlying an open cursor is called a portal. portal names are exposed in the client protocol: a client can fetch rows directly from an open portal, if it knows the portal name. when creating a cursor with DECLARE, the portal name is the same as the cursor name.
you can see all available cursors by querying the pg_cursors system view. ๐ซถ
๐ EXAMPLES ๐
to declare a cursor:
DECLARE liahona CURSOR FOR SELECT * FROM films;
see FETCH(7) for more examples of cursor usage.
๐ COMPATIBILITY ๐
the SQL standard allows cursors only in embedded SQL and in modules. PostgreSQL permits cursors to be used interactively.
according to the SQL standard, changes made to insensitive cursors by UPDATE ... WHERE CURRENT OF and DELETE ... WHERE CURRENT OF statements are visible in that same cursor. PostgreSQL treats these statements like all other data changing statements in that they are not visible in insensitive cursors.
binary cursors are a PostgreSQL extension. โจ
๐ฆ SEE ALSO ๐ฆ
k bye bestie! ๐ this was the DECLARE(7) page from PostgreSQL 16.15, dated 2026 โ now go declare a cursor and slay. ๐โจ
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms