OFFSET and FETCH allow you to skip a number of rows and limit the number of rows returned.
Basic syntax:
- OFFSET n ROWS → Skip the first n rows.
- FETCH NEXT m ROWS ONLY → Return the next m rows.
- ORDER BY is required when using OFFSET FETCH.
Step 1: Example table
Assume the Employees table:
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 1 | John | Doe | IT | 5000 |
| 2 | Jane | Smith | HR | 4500 |
| 3 | Mike | Brown | IT | 6000 |
| 4 | Sara | White | HR | 4700 |
| 5 | Tom | Green | IT | 5200 |
Step 2: Retrieve first 2 rows
Result:
| EmployeeID | FirstName | Salary |
|---|---|---|
| 2 | Jane | 4500 |
| 4 | Sara | 4700 |
OFFSET 0 ROWSmeans start from the first row, then fetch 2 rows.
Step 3: Skip first 2 rows and get next 2
Result:
| EmployeeID | FirstName | Salary |
|---|---|---|
| 1 | John | 5000 |
| 5 | Tom | 5200 |
OFFSET 2 ROWSskips the first 2 lowest salaries.
Step 4: Using only OFFSET
You can also skip rows without limiting:
Result: (skips first 3 rows, returns the rest)
| EmployeeID | FirstName | Salary |
|---|---|---|
| 5 | Tom | 5200 |
| 3 | Mike | 6000 |
FETCHis optional; if omitted, all remaining rows afterOFFSETare returned.
Step 5: Using OFFSET FETCH for pagination
Example: Page size = 2 rows, Page 2
