Queries

SOQL OFFSET

Offsetting Results

SOQL OFFSET skips records for pagination with limits.

Introduction to SOQL OFFSET

In Salesforce Object Query Language (SOQL), the OFFSET clause is used to skip a specified number of rows in a query result. This is particularly useful for implementing pagination in applications, allowing users to view data in manageable chunks. By combining OFFSET with LIMIT, you can efficiently handle large datasets.

Basic Syntax of SOQL OFFSET

The OFFSET clause is used along with a query to specify the number of rows to skip before starting to return rows from the query. Here is the basic syntax:

Using OFFSET for Pagination

Pagination is essential when displaying large amounts of data to users. The OFFSET clause helps achieve this by skipping records that have already been displayed. Consider the following example:

This query fetches the second set of 10 records from the Contact object, skipping the first 10 records. This is useful in a paginated view where the first page shows the first 10 results, and the second page shows the next 10 results.

Limitations of SOQL OFFSET

While OFFSET is powerful, it does have limitations. For instance, there is a maximum limit on the number of records that can be skipped, which is 2,000. Additionally, using OFFSET can affect query performance, especially with large datasets, as it still processes the skipped rows.

Best Practices with SOQL OFFSET

To optimize the use of OFFSET, consider the following best practices:

  • Use OFFSET in conjunction with LIMIT to control the number of records returned.
  • Ensure your queries are optimized and indexed properly to minimize performance issues.
  • Avoid using OFFSET with very large datasets.