Sub topic 10
Query records with SOQL
SOQL (Salesforce Object Query Language) reads records from an org. The CLI runs a SOQL string against an org and prints the matching records. This chapter covers sf data query: the flags you will use most, how shell quoting affects a query, and how to query relationships, aggregates, deleted records, and the Tooling API.
This chapter assumes you have already authorized an org and set a default target org. It also assumes you know basic SOQL: SELECT, FROM, WHERE, ORDER BY, and LIMIT. If sf org display does not show a connected org, go back to the chapters on authorization and defaults first.
How `sf data query` works
The command sends your SOQL to the org's API and formats the response. It does not parse SOQL itself, so the org reports any syntax error or unknown field.
sf data query --query "SELECT Id, Name FROM Account LIMIT 5"The command uses the default target org. If no default is set, it fails and asks for a target org. To query a different org for one command, pass --target-org (short form -o) with an alias or username:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --target-org myscratchThe --target-org flag overrides the default for that command only. It does not change your configuration.
The next diagram shows the path a query takes.
The flags you will use most
| Flag | Short | Purpose |
|---|---|---|
| `--query` | `-q` | The SOQL string to run |
| `--file` | `-f` | Read the SOQL from a file instead |
| `--target-org` | `-o` | Org to query, instead of the default |
| `--result-format` | `-r` | Output as `human`, `csv`, or `json` |
| `--use-tooling-api` | `-t` | Query Tooling API objects |
| `--all-rows` | Include deleted and archived records | |
| `--json` | Wrap the whole command result in JSON |
You must give either --query or --file, not both. Run sf data query --help to see the flags your installed version supports. Flags are added and renamed between releases.
Filtering and ordering
A WHERE clause with a string literal needs single quotes around the value. The simplest approach is to wrap the whole query in double quotes and keep SOQL's single quotes inside:
sf data query --query "SELECT Id, Name, Industry FROM Account WHERE Industry = 'Technology' ORDER BY Name LIMIT 10"The result is a table with one column for each field you selected, followed by a line giving the total record count. If nothing matches, the CLI prints a message saying no records were found. That is not an error, and the exit code is still 0.
Quoting problems
Most beginner failures with this command come from the shell, not from SOQL. The shell processes your command line before the CLI receives it.
- In bash and zsh, double quotes still expand
$and backticks. A query containing$or a backtick can be altered before it reaches the CLI. Use single quotes around the whole query in that case, and avoid single quotes inside it. - A single-quoted bash string cannot contain a single quote. If you need both, put the query in a file and use
--file. - In Windows PowerShell and Command Prompt, quoting rules differ. Double quotes around the query with single quotes inside generally work, but nested double quotes need escaping.
Putting the query in a file avoids almost all of these problems:
cat > recent-contacts.soql <<'EOF'
SELECT Id, FirstName, LastName, Account.Name
FROM Contact
WHERE LastName != 'Smith'
ORDER BY CreatedDate DESC
LIMIT 20
EOF
sf data query --file recent-contacts.soqlThe quoted 'EOF' stops the shell from expanding anything inside the heredoc. A file also keeps long queries readable and lets you commit them to version control.
Relationship queries
SOQL follows lookups and master-detail relationships with dot notation. The CLI flattens these into dotted column names:
sf data query --query "SELECT Id, Name, Owner.Name, Owner.Profile.Name FROM Account LIMIT 5"The columns appear as Owner.Name and Owner.Profile.Name. SOQL allows at most five levels of parent traversal, and that limit applies equally from the CLI.
Child-to-parent queries flatten well. Parent-to-child subqueries are harder to display, because each parent row contains a list of child records:
sf data query --query "SELECT Name, (SELECT LastName FROM Contacts) FROM Account LIMIT 3"The human table shows the child records in a flattened layout, and the output can be hard to read. If you need to process subquery results, use --result-format json or --json, where the nested structure is preserved.
Aggregate queries
Aggregate functions such as COUNT(), SUM(), and MAX() work, but column naming depends on the query. A bare COUNT() returns a total rather than records:
sf data query --query "SELECT COUNT() FROM Contact"When you aggregate with GROUP BY and do not give aliases, Salesforce names the result columns expr0, expr1, and so on. Add aliases to get readable columns:
sf data query --query "SELECT Industry, COUNT(Id) total FROM Account GROUP BY Industry ORDER BY COUNT(Id) DESC"The alias total follows the aggregate expression with no AS keyword. In SOQL, an alias is written directly after the expression.
Choosing an output format
The --result-format flag controls how records print:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --result-format csvUse csv to paste into a spreadsheet or redirect to a file:
sf data query --query "SELECT Id, Name FROM Account" --result-format csv > accounts.csvRedirection saves the command's standard output. Warnings and progress messages go to standard error, so they do not end up in your CSV file.
--result-format json and --json are different. The first changes only how the records are printed. The second wraps the entire command result, including status and result metadata, in a JSON envelope for scripts. The later chapter on JSON output covers that envelope in detail. Here, remember that --json is the right choice when a script needs to check whether the command succeeded.
Deleted records, Tooling API, and large results
Records in the Recycle Bin are excluded by default. Add --all-rows to include them. This is the CLI equivalent of ALL ROWS in SOQL. Combine it with WHERE IsDeleted = true to see only deleted records:
sf data query --query "SELECT Id, Name, IsDeleted FROM Account WHERE IsDeleted = true" --all-rowsSome objects live in the Tooling API rather than the standard API. Examples are ApexClass, ApexTrigger, and CustomField. Querying them requires --use-tooling-api:
sf data query --use-tooling-api --query "SELECT Id, Name, ApiVersion FROM ApexClass ORDER BY Name"Without the flag, the CLI reports that the object does not exist, even though it does exist in the Tooling API. If you see "sObject type not supported" for a metadata-related object, add the flag.
For very large result sets, a plain query pages through the REST API and can be slow. Newer CLI versions provide bulk commands for large exports, such as sf data export bulk. Check sf data --help for the commands your version includes, and prefer them when you need hundreds of thousands of records.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No default environment found` or a similar message about the target org | No default `target-org` and no `--target-org` flag | Run `sf config set target-org myorg` or pass `-o` |
| `INVALID_FIELD` | Misspelled field, a custom field missing the `__c` suffix, or a field the user cannot see | Check the field's API name and field-level security |
| `MALFORMED_QUERY` | SOQL syntax error, often from shell quoting that dropped part of the query | Move the query to a file and use `--file` |
| `sObject type 'X' is not supported` | Tooling API object queried without the flag | Add `--use-tooling-api` |
| Quotes appear to vanish | The shell removed them before the CLI saw them | Check the quoting rules for your shell, or use a file |
When you debug, print the query as your shell sees it. For example, run echo "SELECT Id FROM Account WHERE Name = 'Acme'" and confirm the output matches what you intended.
Putting it together
This script runs a query as part of a larger workflow. It stops with an error if the query fails and prints the number of matching rows:
#!/usr/bin/env bash
set -euo pipefail
sf data query \
--query "SELECT Id, Name FROM Account WHERE Industry = 'Technology'" \
--result-format csv > tech-accounts.csv
# Subtract one line for the CSV header row
echo "Rows: $(( $(wc -l < tech-accounts.csv) - 1 ))"The pipefail option makes the script fail if the CLI command fails, so you do not get an empty file and a success message.
Exercise
You run sf data query --query "SELECT Id, Name FROM ApexClass" and get an error saying the object is not supported. What is the cause, and what is the fix?
Show answer
ApexClass is a Tooling API object, and sf data query uses the standard API by default. Add the --use-tooling-api flag: sf data query --use-tooling-api --query "SELECT Id, Name FROM ApexClass".
Exercise
A query containing the text WHERE Name = 'O'Brien' fails when you type it directly in bash. Describe a reliable way to run it, and say how the quote should be written in SOQL.
Show answer
In SOQL, escape the apostrophe with a backslash, so the clause reads Name = 'O\'Brien'. Put the whole query in a file with a quoted heredoc (<<'EOF') so the shell does not alter the backslash or quotes, then run sf data query --file query.soql.
Exercise
What is the difference between --result-format json and --json, and which one should a script use to detect failures?
Show answer
--result-format json changes only how the records are printed. --json wraps the whole command result, including its status, in a JSON envelope. A script should use --json and also check the exit code, because the envelope reports success or failure in a form that tools such as jq can read.