Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL OFFSET Clause

The `OFFSET` clause in MySQL is used to skip a specified number of rows before starting to return rows from a query. It is often used in conjunction with the `LIMIT` clause to paginate results.

Usage

The `OFFSET` clause is typically used to control the starting point of data retrieval in a data set. It helps in retrieving data from a specific row number, enabling efficient pagination.

sql
SELECT column1, column2, ...
FROM table_name
LIMIT row_count OFFSET offset_value;

In this syntax, `OFFSET offset_value` specifies the number of rows to skip before starting to return the rows.

Examples

1. Basic Offset with Limit

sql
SELECT *
FROM products
LIMIT 10 OFFSET 5;

This query retrieves 10 rows from the `products` table, skipping the first 5 rows.

2. Offset Without Limit

sql
SELECT name, price
FROM products
OFFSET 10;

In this example, all rows starting from the 11th row are retrieved from the `products` table, as no limit is set.

3. Pagination

sql
SELECT order_id, order_date, customer_id
FROM orders
ORDER BY order_date DESC
LIMIT 10 OFFSET 20;

This query retrieves 10 orders starting from the 21st most recent order, useful for displaying the third page of results when 10 results per page are shown.

4. Offset with Join and Complex Order By

sql
SELECT p.product_id, p.name, c.category_name
FROM products p
JOIN categories c ON p.category_id = c.category_id
ORDER BY c.category_name ASC, p.name ASC
LIMIT 5 OFFSET 15;

This example shows how `OFFSET` can be used with a complex `ORDER BY` clause and a `JOIN`, retrieving 5 rows starting after skipping the first 15.

Tips and Best Practices

  • Use with `LIMIT`. Always combine `OFFSET` with `LIMIT` to define both the starting point and the number of rows to return.
  • Optimize performance. Large offsets can lead to performance issues. Consider optimizing queries, using indexed columns, or exploring keyset pagination as an alternative for handling large datasets.
  • Negative values. Avoid using negative values with `OFFSET` as it can lead to errors or unexpected behavior.
  • Watch for zero-based index. Remember that `OFFSET` is zero-based, meaning an `OFFSET` of 10 will skip the first 10 rows.
  • Consistent results. Always use `ORDER BY` with `OFFSET` to ensure consistent results, as omitting it can lead to unpredictable row order.
  • Error Handling. Be aware of potential errors when using `OFFSET`, such as exceeding the number of available rows in the dataset.