Name

FETCH Statement

Synopsis

The FETCH statement is one of four commands used in cursor processing, along with DECLARE, OPEN, and CLOSE. Cursors allow you to process queries one row at a time, rather than as a complete set. FETCH positions a cursor on a specific row and retrieves that row from the result set.

Cursors are especially important in relational databases because they are set-based, while most client-centric programming languages are row-based. So cursors allow you to perform operations a single row at a time, to better fit what a client program can do, rather than operate on a whole set of records at once.

Platform

Command

DB2

Supported, with limitations

MySQL

Not supported

Oracle

Supported, with limitations

PostgreSQL

Supported, with variations

SQL Server

Supported, with variations

SQL2003 Syntax

FETCH [ { NEXT | PRIOR | FIRST | LAST |
  { ABSOLUTE | RELATIVE  int } }
  FROM ] cursor_name
[INTO variable1 [, ...] ]

Keywords

NEXT

Tells the cursor to return the record immediately following the current row, and increments the current row to the row returned. FETCH NEXT is the default behavior for FETCH. It retrieves the first record if FETCH is performed as the first fetch against a cursor.

PRIOR

Tells the cursor to return the record immediately preceding the current row and decrements the current row to the row returned. FETCH PRIOR does not retrieve a record if it is performed as the first fetch against the cursor.

FIRST

Tells the cursor to return the first record in ...

Get SQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.