FETCH

Function

FETCH retrieves data using a previously-created cursor.

A cursor has an associated position, which is used by FETCH. The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result.

Precautions

Syntax

1
FETCH [ direction { FROM | IN } ] cursor_name;

The direction clause specifies optional parameters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
NEXT
   | PRIOR
   | FIRST
   | LAST
   | ABSOLUTE count
   | RELATIVE count
   | count
   | ALL
   | FORWARD
   | FORWARD count
   | FORWARD ALL
   | BACKWARD
   | BACKWARD count
   | BACKWARD ALL

Parameter Description

Examples

Example 1: Run the SELECT statement to read a table using a cursor.

Set up the cursor1 cursor.

1
CURSOR cursor1 FOR SELECT * FROM tpcds.customer_address ORDER BY 1;

Fetch the first three rows from cursor1.

1
2
3
4
5
6
7
FETCH FORWARD 3 FROM cursor1;
 ca_address_sk |  ca_address_id   | ca_street_number |   ca_street_name   | ca_street_type  | ca_suite_number |     ca_city     |    ca_county    | ca_state |   ca_zip   |  ca_country   | ca_gmt_offset |   ca_location_type   
---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+----------------------
             1 | AAAAAAAABAAAAAAA | 18               | Jackson            | Parkway         | Suite 280       | Fairfield       | Maricopa County | AZ       | 86192      | United States |         -7.00 | condo               
             2 | AAAAAAAACAAAAAAA | 362              | Washington 6th     | RD              | Suite 80        | Fairview        | Taos County     | NM       | 85709      | United States |         -7.00 | condo               
             3 | AAAAAAAADAAAAAAA | 585              | Dogwood Washington | Circle          | Suite Q         | Pleasant Valley | York County     | PA       | 12477      | United States |         -5.00 | single family       
(3 rows)

Example 2: Use a cursor to read the content in the VALUES clause.

Set up the cursor cursor2.

1
CURSOR cursor2 FOR VALUES(1,2),(0,3) ORDER BY 1;

Fetch the first two rows from cursor2.

1
2
3
4
5
6
FETCH FORWARD 2 FROM cursor2;
column1 | column2
---------+---------
0 |       3
1 |       2
(2 rows)

Helpful Links

CLOSE, MOVE, CURSOR