DECLARE(7)

๐Ÿ’– DECLARE(7) ๐Ÿ’–

okay so bestie, pull up a chair, because we're talking about DECLARE โ€” the PostgreSQL 18.6 manual page that lets you define a cursor. and yes it's giving "define a cursor" in the NAME section, we love a straightforward queen. let's get into it ๐ŸŽ€


โœจ NAME โœจ

DECLARE โ€” define a cursor. that's it. that's the whole name. iconic brevity, no notes ๐Ÿ’…


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
    CURSOR [ { WITH | WITHOUT } HOLD ] FOR query

๐ŸŒธ DESCRIPTION ๐ŸŒธ

DECLARE lets a user create cursors, which you can use to pull a small number of rows at a time out of a bigger query. once the cursor exists, you fetch rows from it using FETCH. literally that's the whole vibe: little sips instead of chugging the entire result set ๐Ÿ“

Note โ€” this page is about cursors at the SQL command level. if you're trying to use cursors inside a PL/pgSQL function, the rules are different โ€” go look at Section 41.7 instead. don't mix them up bestie, they are not the same thing ๐Ÿ™ˆ

๐Ÿ‘‘ PARAMETERS ๐Ÿ‘‘

  • name โ€” the name of the cursor you're creating. it has to be different from every other active cursor name in the session. no duplicate names, no stealing someone else's handle ๐Ÿ’€
  • BINARY โ€” makes the cursor return data in binary rather than in text format.
  • ASENSITIVE
  • INSENSITIVE โ€” cursor sensitivity decides whether changes to the data underneath the cursor โ€” changes made in the same transaction, after the cursor was declared โ€” are visible in the cursor. INSENSITIVE means they are not visible. ASENSITIVE means the behavior is implementation-dependent. there's a third behavior, SENSITIVE, meaning such changes are visible in the cursor, and it 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. periodt.
  • SCROLL
  • NO SCROLL โ€” SCROLL says the cursor can retrieve rows in a nonsequential fashion (like, backward). depending on how complex the query's execution plan is, specifying SCROLL might impose a performance penalty on the query's execution time. NO SCROLL says the cursor cannot retrieve rows in a nonsequential fashion. the default is to allow scrolling in some cases โ€” and that is not the same as specifying SCROLL. see Notes below for the deets ๐Ÿ”ฅ
  • WITH HOLD
  • WITHOUT HOLD โ€” WITH HOLD says the cursor can keep being used after the transaction that created it successfully commits. WITHOUT HOLD says the cursor cannot be used outside the transaction that created it. if neither WITHOUT HOLD nor WITH HOLD is specified, then WITHOUT HOLD is the default.
  • query โ€” a SELECT or VALUES command which will provide the rows to be returned by the cursor.

and a lil bonus fact: the key words ASENSITIVE, BINARY, INSENSITIVE, and SCROLL can appear in any order. slay, flexible ๐Ÿ’–


๐Ÿ’œ NOTES ๐Ÿ’œ

Normal cursors return data in text format, the same as a SELECT would produce. the BINARY option says the cursor should return data in binary format. this reduces conversion effort for both the server and the 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). not me getting a whole byte-order lesson in the middle of a manpage ๐Ÿ˜ญ

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 a FETCH command, the Bind protocol message specifies whether data is to be retrieved in text or binary format. this choice overrides the way that the cursor is defined. so the concept of a binary cursor as such is obsolete when using extended query protocol โ€” any cursor can be treated as either text or binary. wild but true โœจ

Unless WITH HOLD is specified, the cursor created by this command can only be used within the current transaction. so 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, bestie ๐Ÿซถ

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 โ€” and this is the important part โ€” 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. no exceptions, no loopholes ๐Ÿ’…

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 36.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 specify NO SCROLL for a query involving volatile functions. if that is not practical, one workaround is to declare the cursor SCROLL WITH HOLD and 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. one time only, like a good pop star's tour ๐ŸŒˆ

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 use FOR UPDATE if the cursor is intended to be used with UPDATE ... WHERE CURRENT OF or DELETE ... WHERE CURRENT OF. using FOR UPDATE prevents other sessions from changing the rows between the time they are fetched and the time they are updated. without FOR UPDATE, a subsequent WHERE CURRENT OF command will have no effect if the row was changed since the cursor was created. ๐Ÿ’€
another reason to use FOR UPDATE is that without it, a subsequent WHERE CURRENT OF might 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 or ORDER 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. if FOR UPDATE is specified, the cursor is guaranteed to be updatable.
the main reason not to use FOR UPDATE with WHERE CURRENT OF is 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. read them twice, babe ๐Ÿ™ˆ

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. cute, matching set ๐ŸŽ€

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. go look, there's more content over there ๐Ÿฆ‹


๐ŸŒˆ 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 ๐Ÿ”ฅ


and that's the whole page bestie ๐Ÿ’– this was PostgreSQL 18.6 documentation, dated 2026, and it ate, no crumbs left. go declare a cursor, you've got this ๐Ÿ‘‘โœจ