Sub topic 13
Paging through query results
This chapter assumes you can already create a bulk query job and poll it until it reaches JobComplete. It covers what happens next: reading a result set that may hold millions of rows, one page at a time.
Why results come in pages
A bulk query job runs on the server and stores its output. You then download that output with a GET to the job's results resource. A single response can't carry an unlimited number of rows. A huge response risks a client or gateway timeout, and it forces your program to hold everything in memory.
Salesforce therefore returns the results in pages. Each response carries one page of CSV, plus a response header that tells you where the next page starts. You repeat the request until the header says there are no more pages.
Two things follow from this design:
- The query runs once. Paging only reads stored output, so it never re-executes your SOQL and never shifts rows between pages.
- You can only page after the job is
JobComplete. Requesting results from a job that is still running or has failed returns an error instead of data.
The request and the response headers
The results call looks like this:
curl -D - "$INSTANCE_URL/services/data/v62.0/jobs/query/$QUERY_JOB_ID/results?maxRecords=50000" \
-H "Authorization: Bearer $ACCESS_TOKEN"The -D - option prints the response headers to the terminal, which you need here because the paging information is in the headers and not in the body. Two headers matter:
| Header | Meaning |
|---|---|
| `Sforce-Locator` | An opaque token that marks the start of the next page. The value `null` (or an absent header) means this was the last page. |
| `Sforce-NumberOfRecords` | The number of records in this page. |
The request has two query parameters:
| Parameter | Meaning |
|---|---|
| `maxRecords` | The most records you want in this page. Lower it if pages time out or are too big for your client. |
| `locator` | The value of `Sforce-Locator` from the previous response. Leave it out on the first request. |
The body of every page is CSV, and every page starts with its own header row of column names. Keep that in mind when you join pages into one file, because naive concatenation would put the header row in the middle of your data.
The paging flow
The first request has no locator. Each later request passes back the locator from the response before it.
Treat the locator as opaque
The locator is a string you copy from one response into the next request. Don't parse it, build it yourself, or assume it increases. Its format is not documented as stable, so any code that depends on its shape can break without notice.
Pass it back exactly as received. If it contains characters that need URL encoding, let your HTTP library do the encoding. In Python, pass it through the params argument of requests instead of pasting it into the URL by hand.
A complete paging script
The script below creates a query job, waits for it to finish, and then downloads every page into one CSV file. It writes the header row once and strips it from later pages.
import os
import time
import requests
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
base = f"{instance}/services/data/v62.0/jobs/query"
auth = {"Authorization": f"Bearer {token}"}
job = requests.post(
base,
headers=auth,
json={"operation": "query", "query": "SELECT Id, Name FROM Account"},
)
job.raise_for_status()
job_id = job.json()["id"]
while True:
resp = requests.get(f"{base}/{job_id}", headers=auth)
resp.raise_for_status()
info = resp.json()
if info["state"] in ("JobComplete", "Failed", "Aborted"):
break
time.sleep(5)
if info["state"] != "JobComplete":
raise SystemExit(f"Query job ended in state {info['state']}")
locator = None
first_page = True
total = 0
with open("accounts.csv", "wb") as out:
while True:
params = {"maxRecords": 50000}
if locator:
params["locator"] = locator
page = requests.get(
f"{base}/{job_id}/results", headers=auth, params=params
)
page.raise_for_status()
body = page.content
if first_page:
out.write(body)
first_page = False
else:
# Drop this page's repeated header row.
parts = body.split(b"\n", 1)
if len(parts) == 2:
out.write(parts[1])
total += int(page.headers.get("Sforce-NumberOfRecords", 0))
locator = page.headers.get("Sforce-Locator")
if not locator or locator == "null":
break
print(f"Downloaded {total} records")Some details of this script are worth noting:
- The loop ends on
locatorbeing missing or the string"null". Check for both, because the header can arrive as text and not as an empty value. - Splitting on the first
\nis safe for the header row, because column names don't contain quoted line breaks. The header is removed before any record data begins. - The script reads each page into memory with
page.content. One page at 50,000 records is usually fine. If your rows are very wide, lowermaxRecordsor stream the response withstream=Trueanditer_content. - The count comes from
Sforce-NumberOfRecords, so you can compare it withnumberRecordsProcessedfrom the job info as a sanity check.
Choosing maxRecords
There is no single best value. Pick it by the size of your rows and the reliability of your network.
- A large value means fewer requests, but each response is bigger and takes longer. A very large page can hit a timeout before it finishes.
- A small value means more requests and more header parsing, but each failure costs less to retry.
- Rows with long text fields or many columns weigh far more than narrow rows. A value that suits
SELECT Id FROM Accountmay be too large for a query that returns twenty columns.
Start with a moderate value such as 50,000 and adjust based on observed response times. Salesforce also applies its own size limits to a page regardless of what you ask for, so a page can come back with fewer records than maxRecords. Never assume that a short page means the last page. Only the locator tells you that.
Retrying a failed page
A network error in the middle of paging should not force you to start over. Because the results are stored, you can repeat the same request with the same locator and get the same page again.
Keep track of the locator that produced the page you are fetching. If the request fails, retry with that value. Only advance to the new locator after you have safely written the current page to disk.
This also lets you resume across program runs. If you save the last good locator along with the job ID, a restarted program can continue from that point, as long as the stored results still exist. Salesforce keeps query results for a limited time (check the current documentation for the retention period), so don't rely on a job ID that is days old.
Common mistakes
- Concatenating pages without removing headers. The result is a file with column names repeated in the data, which breaks imports. Strip the header from every page after the first.
- Stopping when a page is short. Pages can be smaller than
maxRecords. Stop only whenSforce-Locatorisnull. - Reading results too early. Requesting results before the job is
JobCompletefails. Poll the job first. - Ignoring the headers. With
curlyou need-D -to see them. With a library, readresponse.headers, not the body. - Building the locator by hand. The value is opaque. Copy it exactly.
- Re-running the query to retry. A failed page doesn't need a new job. Re-request the same locator.
Summary of the loop
- Wait until the query job is
JobComplete. - Request
resultswithmaxRecordsand no locator. - Write the page, removing the header row on every page after the first.
- Read
Sforce-Locatorfrom the response headers. - If it is
null, stop. Otherwise requestresultsagain withlocatorset to that value.
Exercise
Your paging script downloads three pages and produces a CSV in which the line "Id,Name" appears three times, and the record count in the job info matches the data rows plus two. What went wrong, and how do you fix it? Also, how should the script decide it has reached the last page?
Show answer
Each page of results is a complete CSV that starts with its own header row, and the script appended all three pages unchanged. The two extra rows are the repeated headers from pages 2 and 3. Fix it by writing the first page whole and removing the first line from every later page, as in the chapter script. The script should treat a page as the last one only when the Sforce-Locator response header is missing or has the value null, and not when the page holds fewer rows than maxRecords.
Exercise
A request for page 7 fails with a network timeout. You still have the locator that you used for that request. What should you do, and why is it safe?
Show answer
Repeat the same request with the same locator, optionally with a smaller maxRecords if timeouts are frequent. It is safe because the query ran once and its output is stored on the server, so paging only reads that stored output. You don't need a new job. Move to the next locator only after the retried page has been written successfully.