BACKWARD is a direction modifier used with the FETCH and MOVE statements in PostgreSQL. It tells the database to retrieve or skip rows in the reverse order of the cursor’s current position. BACKWARD is only valid for scrollable cursors (those declared with the SCROLL option or implicitly scrollable). If the cursor is declared NO SCROLL, attempting to fetch BACKWARD raises an error. When no count is supplied, PostgreSQL defaults to 1 row. A count of ALL or a positive integer indicates how many rows to move or return in reverse. BACKWARD is non-standard SQL and is not available in most other database systems. Cursors are bound to the session and transaction in which they are created, so cursor operations—including BACKWARD—must run inside the same transaction.
cursor_name
(identifier) - The name of an open cursor.count
(integer) - Optional. Number of rows to move or return (defaults to 1). Use ALL for the entire remaining set.FETCH, MOVE, CURSOR, DECLARE, SCROLL, FORWARD, PRIOR
PostgreSQL 7.3
PRIOR is a synonym for BACKWARD 1. Using BACKWARD without a count or using PRIOR returns the single previous row.
No. Cursors are closed at transaction end. Always wrap DECLARE, FETCH, MOVE, and CLOSE in the same transaction.
Yes. Use FETCH BACKWARD ALL FROM cursor_name; to retrieve every row from the current position to the start.
Absolutely. You can FETCH BACKWARD inside a PL/pgSQL loop to iterate through a result set in reverse.