Sub topic 9
Running Bulk API 2.0 query jobs
This chapter assumes you can run curl commands, read JSON, and have an access token and instance URL for an org. The earlier SOQL and Data Loader chapters cover query syntax and CSV handling. Here you will run a query job yourself, which is also what the Salesforce CLI and Data Loader do for large exports.
How a query job works
A Bulk API 2.0 query job is asynchronous. You submit a SOQL query and Salesforce runs it on the server. You then poll the job until it finishes and download the results as a CSV file. Compared with a normal REST query, you don't page through the data with nextRecordsUrl. You also don't hold a connection open while the server works.
The job moves through these states:
Only JobComplete means results can be downloaded. Treat Failed and Aborted as terminal states. Your script should stop on them instead of polling forever.
Choosing the operation
The operation field takes one of two values:
| Operation | Returns | Use it for |
|---|---|---|
| `query` | Active records only | Routine backups of live data |
| `queryAll` | Active, deleted, and archived records | Backups that must include deleted rows |
With queryAll, include IsDeleted in the field list. Without it you can't tell which rows were in the Recycle Bin at export time.
Submitting a job
The request body is JSON. Besides operation, query, and contentType (only CSV is supported), you can set columnDelimiter (for example COMMA or PIPE) and lineEnding (LF or CRLF). Pick LF if the file will be processed on Linux.
Build the body with jq so quotes inside the query are escaped correctly:
curl -sS -X POST "$INSTANCE_URL/services/data/v60.0/jobs/query" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg q "SELECT Id, Name, IsDeleted FROM Account" \
'{operation:"queryAll", query:$q, contentType:"CSV", lineEnding:"LF"}')"The response contains the job id and a state. Keep the id. Every later call uses it.
Query restrictions to plan for
Bulk API 2.0 queries are a subset of SOQL. Check these points before you automate:
- Child subqueries, such as
(SELECT Id FROM Tasks), are not supported in a flat CSV export. Query each child object separately and keep its parent Id field, such asWhatIdorAccountId. - Parent fields such as
Account.Namecan be selected from a child query. For restore purposes, still export the raw lookup Id, because names are not unique. GROUP BY,OFFSET, andTYPEOFare not supported.- Compound fields such as addresses and geolocations may be rejected. Select their component fields, such as
BillingStreetandBillingCity. - Field-level security and sharing still apply. The user behind the token must be able to see every field and record you want in the backup.
If a job fails with a query error, run the same SOQL in the Developer Console to see whether it is valid SOQL before you suspect the bulk job.
Polling and downloading
Poll GET /jobs/query/{id} until state is JobComplete. The status response also reports numberRecordsProcessed, which is useful for logging. Then download from /jobs/query/{id}/results.
Large results are split into pages. Each response carries two headers:
Sforce-NumberOfRecordsis the number of rows in this page.Sforce-Locatoris a token for the next page, or the stringnullon the last page.
Pass the locator back as ?locator=.... You can also set maxRecords on the request to control page size. Every page starts with its own CSV header row, so when you join pages you must skip that row on every page after the first.
The following script does the whole sequence. It needs curl and jq, plus the two environment variables.
#!/usr/bin/env bash
set -euo pipefail
: "${INSTANCE_URL:?set INSTANCE_URL}" "${ACCESS_TOKEN:?set ACCESS_TOKEN}"
API="$INSTANCE_URL/services/data/v60.0/jobs/query"
AUTH="Authorization: Bearer $ACCESS_TOKEN"
QUERY="SELECT Id, Name, Industry, IsDeleted, LastModifiedDate FROM Account"
OUT="accounts.csv"
JOB_ID="$(curl -sS -X POST "$API" \
-H "$AUTH" -H "Content-Type: application/json" \
-d "$(jq -n --arg q "$QUERY" \
'{operation:"queryAll", query:$q, contentType:"CSV", lineEnding:"LF"}')" \
| jq -r '.id')"
echo "Created job $JOB_ID"
while true; do
STATE="$(curl -sS "$API/$JOB_ID" -H "$AUTH" | jq -r '.state')"
echo "State: $STATE"
case "$STATE" in
JobComplete) break ;;
Failed|Aborted) echo "Job ended as $STATE" >&2; exit 1 ;;
esac
sleep 10
done
: > "$OUT"
LOCATOR=""
FIRST=1
while [ "$LOCATOR" != "null" ]; do
URL="$API/$JOB_ID/results?maxRecords=50000"
if [ -n "$LOCATOR" ]; then URL="$URL&locator=$LOCATOR"; fi
curl -sS "$URL" -H "$AUTH" -D headers.txt -o page.csv
LOCATOR="$(grep -i '^Sforce-Locator:' headers.txt | awk '{print $2}' | tr -d '\r')"
LOCATOR="${LOCATOR:-null}"
if [ "$FIRST" -eq 1 ]; then
cat page.csv >> "$OUT"; FIRST=0
else
tail -n +2 page.csv >> "$OUT"
fi
done
rm -f headers.txt page.csv
echo "Wrote $OUT"The LOCATOR="${LOCATOR:-null}" line is a safeguard. If the header is missing for any reason, the loop ends instead of requesting the same page forever.
Common errors
- 401 or
INVALID_SESSION_ID. The access token expired. A long export can outlive a short-lived token, so refresh it between phases. - Job stuck in
InProgress. Large objects take time, and the job runs on shared infrastructure. Poll at a steady interval such as 10 to 30 seconds. Don't poll in a tight loop, because every status call counts against your API usage. - Row count lower than expected. Check whether you used
querywhere you neededqueryAll. Also check the user's sharing access, which limits what a job can see. - Broken CSV rows. Text fields can contain commas, quotes, and line breaks. Parse the file with a real CSV reader, not
cutorawk. Don't count rows withwc -l, because one record can span several lines. - Results missing later. Salesforce removes job results after a retention period, currently seven days. Download them promptly and store them as described in the storage chapter.
You can delete a finished job with DELETE /jobs/query/{id}, and abort a running one with PATCH and a body of {"state":"Aborted"}.
Where this fits
Data Loader and the sf data export bulk command use this same API. Writing the calls yourself helps when you need to run exports from a language other than the CLI, when you want direct control over paging and retries, or when you are diagnosing why a tool-driven export failed. For small objects the plain sf data query command from the previous chapter is simpler. Use a query job when row counts are large or the results are too big for a single synchronous response.
Exercise
Your script downloads a three-page result and the final CSV has the header row repeated twice in the middle of the data. What went wrong, and how do you fix it?
Show answer
Each result page begins with its own header row, and the script appended every page unchanged. Keep the first page whole and skip the first line of every later page, for example with tail -n +2 page.csv >> accounts.csv.
Exercise
A backup must include records that users deleted yesterday. Which operation and which field do you use, and why?
Show answer
Use the queryAll operation, which also returns deleted and archived records. Select IsDeleted so each row shows whether it was deleted when the export ran.
Exercise
You need Contacts together with their Tasks in one backup. Why can't one Bulk API 2.0 query job return both, and what do you do instead?
Show answer
Child subqueries such as (SELECT Id FROM Tasks) are not supported in a flat CSV export. Run one job for Contact and another for Task, and include the lookup Id fields (for example WhoId) in the Task export so the relationships can be rebuilt on restore.