Sub topic 12
Exporting data with bulk query jobs
Earlier chapters covered ingest jobs, which move data into Salesforce. This chapter covers the reverse direction: a bulk query job runs a SOQL query on the server and gives you the result as CSV files.
This chapter assumes you can write SOQL, you have an OAuth access token and instance URL, and you know the ingest job lifecycle from the job model chapter. Paging through large results is covered in the next chapter, so this one stops at the first page.
How a query job differs from an ingest job
A query job uses the same job idea as an ingest job, but it is simpler. You never upload data, so there is no Open state and no UploadComplete call from you. You send the SOQL in the creation request, and Salesforce starts working immediately.
| Aspect | Ingest job | Query job |
|---|---|---|
| Endpoint | `/jobs/ingest` | `/jobs/query` |
| Input | CSV you upload | SOQL in the create request |
| Initial state | `Open` | `UploadComplete` |
| Output | Successful, failed and unprocessed CSVs | One result set, read in pages |
| Operation values | `insert`, `update`, `upsert`, `delete`, `hardDelete` | `query`, `queryAll` |
The job moves through a short lifecycle.
Creating a query job
Send a POST to /services/data/vXX.X/jobs/query. The body needs two fields: operation and query.
curl -X POST "$INSTANCE_URL/services/data/v62.0/jobs/query" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"operation":"query","query":"SELECT Id, Name FROM Account"}'The response is JSON. Save the id value, because every later call uses it. The state field is UploadComplete, which for a query job means "queued".
Optional body fields control the output format:
columnDelimiteris one ofBACKQUOTE,CARET,COMMA(the default),PIPE,SEMICOLONorTAB. Pick a delimiter that does not appear in your data if you plan to parse the file with simple tools.lineEndingisLF(the default) orCRLF.contentTypecan only beCSV.
query and queryAll
query returns only live records, like a normal SOQL query. queryAll also returns soft-deleted records (those with IsDeleted = true) and archived records, such as old Tasks and Events. Use queryAll for audits or for syncing deletions to another system.
SOQL restrictions
Bulk queries accept most SOQL, but some features are not supported. Check the current Bulk API 2.0 documentation for your API version, because this list changes:
GROUP BY,OFFSETandTYPEOFclauses are not supported.- Parent-to-child subqueries, such as
SELECT Id, (SELECT Id FROM Contacts) FROM Account, are not supported. Run a separate query on the child object and join the results yourself. - Child-to-parent fields such as
Account.Nameon a Contact are supported. The CSV header uses the dotted path as the column name. - Compound fields such as
BillingAddresscannot be queried. Select the individual parts instead, for exampleBillingCityandBillingStreet.
Use LIMIT only if you really want a sample. A bulk query is designed to export everything that matches.
Checking job status
Poll the job with a GET on its id:
curl "$INSTANCE_URL/services/data/v62.0/jobs/query/$QUERY_JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"Watch these fields in the response:
stateisUploadComplete,InProgress,JobComplete,FailedorAborted.numberRecordsProcessedgrows while the job runs.errorMessageappears when the state isFailed. A malformed query, for example, usually fails at creation time with an HTTP 400 instead.
JobComplete, Failed and Aborted are terminal states. Stop polling when you see one of them. Poll every 5 to 30 seconds for large exports. Polling every second wastes API calls and gains nothing.
To cancel a job, send a PATCH with {"state":"Aborted"}. To remove a finished job and its stored results, send a DELETE to the same URL. To see recent query jobs in the org, GET /jobs/query.
Downloading results
Once the state is JobComplete, read the data with a GET on /jobs/query/{id}/results. The maxRecords parameter sets the page size.
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 before the CSV body. Two headers matter:
Sforce-NumberOfRecordsis the number of rows in this response.Sforce-Locatoris a token for the next page. When there are no more pages, its value is the stringnull.
The body is plain CSV. The first line holds the column names in the same order as your SELECT list. Fields with no value are empty strings, and values that contain commas, quotes or line breaks are quoted. Load the file with a real CSV parser instead of splitting on commas.
If you do not set maxRecords, Salesforce chooses a page size for you. Paging with the locator is the subject of the next chapter. Until then, treat the first response as one page of a larger set.
A polling script
This Python script creates a query job, waits for it to finish, and saves the first page of results to a file. It reads credentials from environment variables, like the ingest script from the previous chapters.
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"]
deadline = time.time() + 30 * 60
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
if time.time() > deadline:
raise TimeoutError(f"Job {job_id} still {info['state']} after 30 minutes")
time.sleep(10)
if info["state"] != "JobComplete":
raise RuntimeError(f"Job ended as {info['state']}: {info.get('errorMessage')}")
results = requests.get(
f"{base}/{job_id}/results",
headers=auth,
params={"maxRecords": 50000},
stream=True,
)
results.raise_for_status()
with open("accounts.csv", "wb") as out:
for chunk in results.iter_content(chunk_size=1024 * 1024):
out.write(chunk)
print("Rows in this page:", results.headers.get("Sforce-NumberOfRecords"))
print("Next locator:", results.headers.get("Sforce-Locator"))Three choices in this script are worth copying:
- A deadline stops the loop if a job is stuck, instead of polling forever.
- The script checks for
JobCompletebefore it downloads. Calling/resultson a failed job returns an error, not data. stream=Trueanditer_contentwrite the response to disk in chunks. A page of 50,000 wide rows can be large, and you do not want it all in memory.
Common errors and gotchas
- HTTP 400 at creation. The SOQL is invalid or uses an unsupported feature. Test the query in a normal SOQL tool first, then remove any
GROUP BY,OFFSET,TYPEOFor child subquery. - Missing columns. Field-level security applies to the user your token belongs to. Fields that user cannot read cause an error or are left out, depending on the case. Run exports as a user with the access you expect.
- Results disappear. Salesforce keeps job results for a limited time after completion, currently about seven days. Download the data soon after the job finishes, and do not treat the job as long-term storage.
- Timestamps. Date/time values come back in UTC in ISO 8601 format. Convert them in your own code if you need local time.
- Counting rows. To check an export, compare the sum of
Sforce-NumberOfRecordsacross all pages with aSELECT COUNT() FROM ...run through the normal query API. The two numbers can differ if records change while the job runs.
Exercise
You create a query job and its first response shows state "UploadComplete". A colleague says you must now upload a CSV and PATCH the job. Are they right? Which call do you make next, and when can you request results?
Show answer
No. For a query job, UploadComplete means the job is queued, and Salesforce has already started it. There is nothing to upload and no state change to send. Next, poll GET /jobs/query/{id} until the state is JobComplete (and treat Failed or Aborted as errors). Only then call GET /jobs/query/{id}/results, optionally with maxRecords, and read the Sforce-Locator header to see whether another page exists.
Exercise
Your export of Contacts must include records that users deleted last week. Which operation value do you use, and which unsupported feature would you hit if you tried to also fetch each Contact's Cases in the same query?
Show answer
Use "queryAll" instead of "query", because it includes soft-deleted and archived records. Fetching Cases in the same query would need a parent-to-child subquery, which Bulk API 2.0 does not support. Run a second query job on Case, selecting ContactId, and join the two CSV files yourself.