FETCH
FETCH in SQL is used to retrieve a specific row or set of rows from a result set generated by a query. This allows users to manage large amounts of data by selecting only a portion of it. Its usage is common in combination with OFFSET for paging through query results.
Example
Output
Explanation
The FETCH
command in PostgreSQL is used to retrieve rows from a result set one at a time or few at a time. In the example mentioned above, DECLARE
cursor is created for columns from table_sample
. Then, FETCH
command is used to retrieve the next set of rows of the cursor.
Example
Output
Explanation
In this example, a cursor named @MyCursor
is declared along with a variable @MyField
, which will hold data fetched from the cursor. The cursor is filled with rows from MyTable
. Using a while loop, the cursor fetches next row from MyCursor
and prints the value of MyField
until there are no more rows to fetch (indicated by @@FETCH_STATUS = 0
). Once every row has been fetched and printed, the cursor is closed and deallocated.
Example
Output
Explanation
The example declares a cursor c_emp
for a SELECT statement that retrieves employee name and salary for employees with salary greater than 2000. The FETCH
statement gets a single row from the result set of this SELECT statement and stores the data in rec_emp
. The dbms_output.Put_line
procedure is then used to send the output to the client. The rec_emp.ename
and rec_emp.sal
expressions extract the employee name and salary from the fetched row.