Examples of OFFSET and FETCH
SELECT *
FROM T1
ORDER BY COL1
OFFSET 10 ROWSSELECT *
FROM T1
ORDER BY COL1
FETCH FIRST 10 ROWS ONLYOFFSET and FETCH clauses in a derived table and in the outer querySELECT *
FROM (
  SELECT *
  FROM T1
  ORDER BY COL1 DESC
  OFFSET 1 ROW
  FETCH NEXT 10 ROWS ONLY
) a
ORDER BY a.COL1
FETCH FIRST ROW ONLYThe following examples rewrite the FIRST/SKIP examples and ROWS examples earlier in this chapter.
Retrieve the first ten names from the output of a sorted query on the PEOPLE table:
SELECT id, name
FROM People
ORDER BY name ASC
FETCH NEXT 10 ROWS ONLY;Return all records from the PEOPLE table except for the first 10 names:
SELECT id, name
FROM People
ORDER BY name ASC
OFFSET 10 ROWS;And this query will return the last 10 records.Contrary to FIRST/SKIP and ROWS we cannot use expressions (including sub-queries).To retrieve the last 10 rows, reverse the sort to the first (last) 10 rows, and then sort in the right order.
SELECT id, name
FROM (
  SELECT id, name
  FROM People
  ORDER BY name DESC
  FETCH FIRST 10 ROWS ONLY
) a
ORDER BY name ASC;This one will return rows 81-100 from the PEOPLE table:
SELECT id, name
FROM People
ORDER BY name ASC
OFFSET 80 ROWS
FETCH NEXT 20 ROWS;