The OFFSET clause determines the starting position of the records to be retrieved.
OFFSET n {ROWS | ROW}nis an unsigned integer.- If
nis greater than the total number of rows available, no results are returned. ROWSandROWare interchangeable.- Cannot be used in subqueries.
SELECT emp_id, last_name, first_name
FROM employees
ORDER BY last_name, first_name
OFFSET 25 ROWS;This query skips the first 25 records and starts retrieval from the 26th record.
OFFSET 0: Returns all rows without skipping.OFFSET nwheren > total_rows: Returns an empty result set without an error.
The FETCH FIRST clause limits the number of rows returned.
FETCH FIRST [ n [ PERCENT ] ] { ROWS | ROW } {ONLY | WITH TIES }ndefines the number of rows to return. Default is1if omitted.- Fetch size
nmust be a value greater than or equal to 0. PERCENTfetchesn%of the total result set.WITH TIESensures that all rows with the same ordering values are included.- Cannot be used in subqueries.
SELECT emp_id, last_name, first_name
FROM employees
ORDER BY last_name, first_name
FETCH FIRST 10 ROWS ONLY;This query returns the first 10 records from the result set.
FETCH FIRST 0 ROWS ONLY: Returns an empty result set without an error.FETCH FIRST 100 PERCENT ROWS ONLY: Returns all rows.- Use without
ORDER BY: Retrieves an arbitrary subset of rows due to undefined ordering.
Both clauses can be combined to implement pagination.
SELECT emp_id, last_name, first_name
FROM employees
ORDER BY last_name, first_name
OFFSET 25 ROWS FETCH FIRST 10 ROWS ONLY;This query retrieves 10 rows starting from the 26th record.
If WITH TIES is used, additional rows sharing the same values as the last retrieved row (based on ORDER BY) are included.
SELECT emp_id, last_name, first_name
FROM employees
ORDER BY last_name, first_name
FETCH FIRST 10 ROWS WITH TIES;This ensures all employees with the same last name and first name as the 10th record are included.
- Without
ORDER BY:WITH TIEShas no effect. - More rows than
nreturned: If multiple rows share the same value at the cutoff point, additional rows are returned.
- Sorting Requirement: The
ORDER BYclause is essential to ensure deterministic results. - Offset Handling: Large
OFFSETvalues cause inefficiency since all preceding rows are still processed internally before skipping. - Best Practices: Use indexed fields in
ORDER BYto optimize performance.
- Subqueries:
OFFSETandFETCH FIRSTcannot be used in subqueries. - Updates & Deletes:
OFFSETandFETCH FIRSTare only valid inSELECTstatements.