Sub topic 8
Exporting from the command line with the Salesforce CLI
This chapter assumes you can write a basic SOQL query (covered in the SOQL chapter). It also assumes you have an org with an administrator profile and are comfortable in a terminal. You will authorize the CLI against an org, export one object, handle failures, and extend the command into a repeatable job.
What the CLI gives you
The Salesforce CLI is the sf command. It wraps the Salesforce APIs, so a single command can authenticate, run a SOQL query, and write the result as CSV or JSON. Compared with Data Loader, it has no graphical interface, which makes it easy to script, schedule, and keep in version control.
Use it when you want:
- A repeatable export you can run the same way every time.
- Output you can pipe into other tools.
- One tool for both data (this chapter) and metadata (a later chapter).
Authorizing an org
The CLI refers to orgs by alias. Authorize once, then reuse the alias in every command.
sf org login web --alias my-prod-alias
sf org listsf org login web opens a browser for interactive login. That works on your laptop but not on a scheduler. For unattended runs, use the JWT flow, which authenticates with a connected app and a private key instead of a browser:
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username [email protected] \
--alias my-prod-aliasRun backups as a dedicated integration user. Give that user "View All Data" (or the narrowest permissions that still read every object you back up). Otherwise field-level security and sharing rules silently remove rows and columns from your export.
Exporting one object
The basic command runs a query and prints CSV to standard output:
sf data query \
--query "SELECT Id, Name, Industry FROM Account" \
--result-format csv \
--target-org my-prod-alias > accounts.csvThe flags that matter:
| Flag | Purpose |
|---|---|
| `--query` (`-q`) | The SOQL statement. |
| `--result-format` | `human` (default table), `csv`, or `json`. Use `csv` for backups. |
| `--target-org` (`-o`) | The org alias or username. |
| `--all-rows` | Includes deleted and archived records, like `queryAll` in the API. |
| `--json` | Wraps the whole command result, including errors, in JSON. Useful for scripts. |
Always list fields explicitly. SOQL has no SELECT *, and you should not want one: an explicit list makes the export reviewable and stops a new field from changing your file layout without notice.
Incremental exports
Add a filter on LastModifiedDate to export only what changed since the previous run:
SELECT Id, Name, Industry, OwnerId, CreatedDate, LastModifiedDate
FROM Account
WHERE LastModifiedDate >= 2026-01-01T00:00:00Z
ORDER BY LastModifiedDateStore the timestamp of each successful run and use it in the next query. An incremental export does not capture deletions. Use --all-rows and include IsDeleted in the field list so deleted records are visible, or run a periodic full export to reset your baseline.
Child records
A relationship query can read a parent field (Account.Name) and child rows through a subquery:
SELECT Id, FirstName, LastName, Account.Name,
(SELECT Id, Subject FROM Tasks)
FROM Contact
LIMIT 100This is fine for exploring in the terminal. For CSV backups, do not rely on subqueries: a flat file cannot represent nested rows. Export each child object with its own query (for example Task, including its WhoId and WhatId columns) and join by Id later.
Handling failures
Redirecting standard output into a file has a trap. If the query fails halfway, you may be left with an empty or truncated file, and the next step may treat it as a valid backup. Write to a temporary file and move it into place only on success:
sf data query \
--query "SELECT Id, Name, Industry FROM Account" \
--result-format csv \
--target-org my-prod-alias > accounts.csv.tmp \
&& mv accounts.csv.tmp accounts.csvThe CLI exits with a non-zero status on error, so && and set -e both work. Errors go to standard error, so they will not appear in your CSV.
Large result sets
A normal sf data query uses the REST API and pages through results. That is fine for tens of thousands of rows, but it counts against your daily API request allocation and gets slow for millions. For large objects, use a Bulk API 2.0 query job, which runs asynchronously on the server. Recent CLI versions expose this through sf data export bulk. Check sf data export bulk --help on your installed version, because flags differ between releases. The chapter on Bulk API 2.0 shows the underlying REST calls.
Other limits to keep in mind:
- Long text area and rich text fields can make rows very large.
- A query that filters on a non-indexed field over a large object can time out. Filter on
Id,CreatedDate, orLastModifiedDate, or split the export into date ranges. - Compound fields such as
BillingAddresscannot be exported as one CSV column in some tools. Select the individual parts (BillingStreet,BillingCity, and so on).
Scripting a multi-object export
This script writes one CSV per object into a dated folder. It extends the basic command with an atomic write and the --all-rows flag.
#!/usr/bin/env bash
set -euo pipefail
ORG="my-prod-alias"
STAMP="$(date +%Y%m%d)"
DEST="backup/$STAMP"
mkdir -p "$DEST"
for OBJ in Account Contact Opportunity; do
sf data query \
--query "SELECT Id, Name FROM $OBJ" \
--result-format csv \
--all-rows \
--target-org "$ORG" > "$DEST/$OBJ.csv.tmp"
mv "$DEST/$OBJ.csv.tmp" "$DEST/$OBJ.csv"
echo "exported $OBJ"
doneId, Name keeps the example short. A real backup should list every field you need to restore. You can generate that list from the object description with sf sobject describe --sobject Account --target-org my-prod-alias --json.
A scheduler such as cron or a CI job can run this script. The automation chapter covers scheduling and alerting.
A quick completeness check
Count what the org says it has, then count what you wrote:
sf data query \
--query "SELECT COUNT() FROM Account" \
--target-org my-prod-alias \
--jsonThe totalSize field in the JSON is the count. Do not count CSV rows with wc -l. Text fields can contain line breaks inside quoted values, so lines and records differ. Use a CSV parser:
import csv
import sys
with open(sys.argv[1], newline="", encoding="utf-8") as f:
rows = sum(1 for _ in csv.DictReader(f))
print(rows)Run python count_rows.py backup/20261130/Account.csv and compare the number to totalSize. If you export with --all-rows, compare against a count that also includes deleted rows, or the numbers will not match.
The flow at a glance
Common mistakes
- Using
--result-format humanin a script. The table output is truncated for display and is not a valid backup. - Forgetting that the CLI respects the running user's permissions, so a low-privilege user produces an incomplete file with no error.
- Exporting Id values only on parents and not on children, which makes relationships impossible to rebuild.
- Treating a file of zero rows as success. An empty
Account.csvshould fail your script.
Exercise
Your nightly script runs sf data query ... > Account.csv and the network drops partway through. The script's next step uploads Account.csv to storage. What goes wrong, and how do you prevent it?
Show answer
The redirect creates or truncates Account.csv before the query finishes, so a partial or empty file can be uploaded as if it were a good backup. Write to a temporary file, move it to the final name only after the command exits with status 0 (use && or set -e), and check the row count against SELECT COUNT() FROM Account before uploading.
Exercise
You need a CSV of Contacts and their Tasks. Why does one query with a (SELECT Id, Subject FROM Tasks) subquery not work for a CSV backup, and what do you do instead?
Show answer
A flat CSV cannot hold nested child rows. Export Contact and Task as separate files with their own queries, and include the Task columns WhoId and WhatId so the rows can be matched back to their parents by Id.