SQL FETCH is a cursor-control statement defined in the SQL standard. After you DECLARE a cursor and OPEN it, FETCH moves the cursor pointer and copies the current row (or block of rows) into target variables so the application can process them. Orientation options such as NEXT, PRIOR, FIRST, LAST, ABSOLUTE n, and RELATIVE n control which row is fetched. Many databases also support a FETCH clause in SELECT statements (OFFSET … FETCH) for server-side pagination; although the syntax overlaps, the semantics differ: the SELECT version limits rows returned directly to the client instead of working through an application cursor.Key behaviors:- Requires an already OPEN cursor.- Advances the cursor unless the orientation is PRIOR, ABSOLUTE, or RELATIVE.- Returns a status (SQLSTATE or @@FETCH_STATUS) so the application can detect end-of-result.- Works inside transactions; the cursor sees a snapshot consistent with its isolation level.Caveats:- Attempting to FETCH past the end of the result set sets a not-found condition.- Scrollable (bi-directional) fetches need a SCROLL or INSENSITIVE cursor declaration.- Some drivers limit the maximum block size for bulk fetches (e.g., FETCH 100 ROWS).
cursor_name
(identifier) - The name of an already OPEN cursor.orientation
(keyword) - NEXT | PRIOR | FIRST | LAST | ABSOLUTE n | RELATIVE n | n ROWS; controls which row(s) to fetch.target_list
(variables or columns) - One variable per column selected by the cursor.CURSOR, DECLARE CURSOR, OPEN, CLOSE, SCROLL, OFFSET, LIMIT, ROW_NUMBER
SQL-92 (cursor operations); OFFSET … FETCH added in SQL:2008
Standard orientations include NEXT (default), PRIOR, FIRST, LAST, ABSOLUTE n, and RELATIVE n. Some databases add FORWARD n or BACKWARD n variants for block fetches.
After each FETCH, check the not-found indicator. In embedded SQL this is SQLSTATE '02000'; in T-SQL use `@@FETCH_STATUS`; in PL/pgSQL catch the `NO_DATA_FOUND` exception.
Yes. Many databases accept `FETCH NEXT 100 ROWS FROM cur INTO ...` which reduces round-trips. Host variables must be declared as arrays or bulk-collect types.
OFFSET … FETCH is portable across ANSI-compliant systems and supports the optional `FETCH WITH TIES` extension. LIMIT is shorter but proprietary, so prefer OFFSET … FETCH for compatibility.