Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SOQL Pagination for Salesforce API queries

Is there an efficient way to page through results from a SOQL query without bringing all the query results back and then discarding the majority of them?

As an example, I'd like to be able to to page through the complete list of contacts showing 10 records at a time. I don't have the need to sort by any particular field.

like image 355
Daniel Ballinger Avatar asked Oct 02 '09 01:10

Daniel Ballinger


People also ask

How do I optimize SOQL query in Salesforce?

Custom indexes, when used improperly, can actually slow query results. It's best to create filter conditions that are selective so Force.com scans only the rows necessary in the objects your queries target.

What does the Fiscal_year () function do within a SOQL query?

Returns a number representing the fiscal year of a date field. This differs from CALENDAR_YEAR() if your organization uses a fiscal year that does not match the Gregorian calendar.


2 Answers

Currently the most efficient solution I've found that will work with any SOQL query through the partner API is to persist the sObjects returned from the initial QueryResult and the query locator incase a page is requested outside the current results.

This required a level of paging support on top of the Salesforce QueryResult.

I.e. When a page is requested sObjects may be required from:

  • The current (cached) QueryResult
  • A subsequent QueryResult that can be fetched using the query locator
  • A prior QueryResult
  • Some combination of all three.

If the page spans two (or more) QueryResults an artifical QueryResult will need to be created with all the required records.

Update for Spring 2012 Release

Looks like there is new functionality coming that will add OFFSET support to SOQL. E.g.

SELECT Name FROM Merchandise__c WHERE Price__c > 5.0 ORDER BY Name LIMIT 50 OFFSET 100

See Spring '12 Force.com Platform Release - OFFSET added to SOQL (Pilot)

Update for Summer 2012 Release

OFFSET is now GA (General Availability?)

like image 123
Daniel Ballinger Avatar answered Oct 14 '22 02:10

Daniel Ballinger


you can use a auto-number filed to do pagination at server side. this field can be used after 'order by' clause, it can act as a index field.

I've done pagination like what you side. but I got another problem, I can't do sort in server side at the same time. because sort and pagination both need add column after 'order by' clause.

like image 23
Hui Avatar answered Oct 14 '22 00:10

Hui