Sub topic 10
Finding records with SOQL queries
You can already create, read, and update a record when you know its ID. Often you don't. This chapter covers the query endpoint, which finds records by field values using SOQL (Salesforce Object Query Language).
This chapter assumes you can send an authenticated request with a bearer token, build a resource URL from the instance URL and API version, and read a JSON response. The examples use the same SF_INSTANCE_URL, SF_ACCESS_TOKEN, and SF_API_VERSION variables as the earlier chapters.
The query resource
The query resource lives at /services/data/<version>/query. You send a GET request with a q parameter that holds the SOQL statement.
curl -G "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/query" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
--data-urlencode "q=SELECT Id, Name, Industry FROM Account WHERE Industry = 'Banking' LIMIT 10"Two details matter here:
-Gtells curl to put the data in the URL as a query string instead of the body, so the request stays a GET.--data-urlencodeencodes spaces, quotes, and other special characters. A raw SOQL string pasted into a URL usually breaks on the spaces or the'characters.
Unlike the sObject resource, the query resource does not take a record ID. It takes a statement, and the statement decides what comes back.
The shape of a query response
A successful query returns status 200 and a JSON body like this:
{
"totalSize": 2,
"done": true,
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v60.0/sobjects/Account/001xx000003DGb2AAG"
},
"Id": "001xx000003DGb2AAG",
"Name": "Acme Corp",
"Industry": "Banking"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v60.0/sobjects/Account/001xx000003DGb3AAG"
},
"Id": "001xx000003DGb3AAG",
"Name": "Globex",
"Industry": "Banking"
}
]
}| Key | Meaning |
|---|---|
| `totalSize` | Total number of rows the query matches, not only the rows in this response. |
| `done` | `true` when this response holds the last batch. `false` means more batches exist. |
| `records` | The rows in this batch. |
| `attributes` | On each record, the sObject type and the URL of that record's sObject resource. |
| `nextRecordsUrl` | Present only when `done` is `false`. The path for the next batch. |
The attributes object is added by the API and is not a field. Remove it before you send a record back in a POST or PATCH body. Including it in a write causes an error.
Writing SOQL for the REST API
SOQL looks like SQL but has its own rules. These are the ones that cause most mistakes.
- There is no
SELECT *. List each field you want. TheIdfield is not added automatically for every query shape, so include it when you plan to update or delete the rows later. - Object and field names use API names. Custom fields end in
__c, as inRegion__c. - String literals use single quotes.
Industry = "Banking"with double quotes is a malformed query. - Date and datetime literals are not quoted. For example,
CreatedDate > 2026-01-01T00:00:00Z. ORDER BYandLIMITwork as in SQL. WithoutORDER BY, the row order is not guaranteed.- Related records are reached through relationship names. A child-to-parent query uses dot notation:
SELECT Name, Account.Name FROM Contact.
The query runs as the authenticated user. Sharing rules and field-level security apply, so two users can run the same statement and get different rows or hit different "no such column" errors.
Counting rows
Use SELECT COUNT() FROM Account WHERE Industry = 'Banking' to count rows. The count is in totalSize, and records is empty. If you write COUNT(Id) instead, the result comes back as a record with a field named expr0. The two forms look alike but return their numbers in different places.
Large result sets and pagination
The API returns query results in batches. The default batch size is 2,000 records. If the query matches more rows than one batch holds, the response has done: false and a nextRecordsUrl:
{
"totalSize": 5230,
"done": false,
"nextRecordsUrl": "/services/data/v60.0/query/01gxx0000000001AAA-2000",
"records": []
}The records array above is empty only to keep the example short. A real response contains the batch's rows.
To get the next batch, send a GET to the instance URL plus the nextRecordsUrl value. Repeat until done is true. The path contains a query locator, which is a server-side cursor. Treat it as opaque: do not parse it or build it yourself.
You can ask for a smaller batch with the Sforce-Query-Options header, for example Sforce-Query-Options: batchSize=500. The accepted range is 200 to 2,000, and the value is a request, not a guarantee. Smaller batches reduce the memory each response uses. They also increase the number of calls.
The OFFSET clause also exists, but it is capped at 2,000 rows. For a full export, follow nextRecordsUrl instead.
A complete example in Python
This script runs a filtered query, follows every page, and escapes the value that goes into the WHERE clause.
import os
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
headers = {"Authorization": f"Bearer {token}"}
def soql_quote(value):
"""Return value as a SOQL string literal with backslashes and quotes escaped."""
escaped = value.replace("\\", "\\\\").replace("'", "\\'")
return f"'{escaped}'"
def query_all(soql):
"""Yield every record that matches soql, following nextRecordsUrl."""
url = f"{instance_url}/services/data/{version}/query"
params = {"q": soql}
while url:
response = requests.get(url, headers=headers, params=params, timeout=30)
if not response.ok:
raise RuntimeError(f"{response.status_code}: {response.text}")
body = response.json()
yield from body["records"]
next_path = body.get("nextRecordsUrl")
url = f"{instance_url}{next_path}" if next_path else None
params = None # the locator URL already identifies the query
industry = "Banking"
soql = (
"SELECT Id, Name, Industry FROM Account "
f"WHERE Industry = {soql_quote(industry)} "
"ORDER BY Name"
)
count = 0
for record in query_all(soql):
print(record["Id"], record["Name"])
count += 1
print(f"{count} records")Setting params = None after the first call matters. The nextRecordsUrl path already identifies the query, and sending a second q parameter would be wrong.
Query errors
Query failures use the same error format as record operations: a JSON array of objects with message and errorCode. The status is 400 for a bad statement and 401 for a bad session.
| errorCode | Status | Typical cause |
|---|---|---|
| `MALFORMED_QUERY` | 400 | Syntax error, such as double-quoted strings, a missing `FROM`, or a trailing comma. |
| `INVALID_FIELD` | 400 | Misspelled field, a field that does not exist on the object, or a field the user cannot see. |
| `INVALID_TYPE` | 400 | The object in `FROM` does not exist or is not visible to the user. |
| `INVALID_SESSION_ID` | 401 | The access token has expired or is invalid. |
| `QUERY_TIMEOUT` | 400 | The query ran too long, often from a non-selective filter on a large object. |
The message for MALFORMED_QUERY and INVALID_FIELD includes the row and column of the problem and a caret under it. Log the full body so you can see it.
A query that matches nothing is not an error. It returns status 200 with totalSize set to 0 and an empty records array. Check totalSize or the array length before you read records[0].
Practical notes
- Select only what you need. Each extra field increases response size and processing time.
- Filter on indexed fields. Id, Name, lookup fields, and external ID fields are indexed. A filter on an unindexed field of a very large object can be slow or time out.
- Keep the URL short. The statement travels in the URL. Very long statements, such as a WHERE clause with thousands of IDs in an
INlist, can exceed the URL length limit, which is about 16 KB. Split such work into several queries. - Deleted records are excluded. The
queryAllresource at/services/data/<version>/queryAllalso returns soft-deleted and archived records. Use it only when you need them. - Each call counts against API limits. Paging through a large result costs one call per batch, so a bigger batch size means fewer calls.
Exercise
A query returns "totalSize": 4500 and "done": false, and the records array holds 2000 rows. What do you do to get the rest, and why should you not add OFFSET 2000 to the statement instead?
Show answer
Send a GET to the instance URL plus the nextRecordsUrl from the response, and repeat until done is true. That path carries a query locator that the server uses to continue the same query. OFFSET is capped at 2,000 rows, so it cannot reach rows beyond that point, and it restarts the query on each call.
Exercise
Your script builds WHERE Name = 'O'Brien Ltd' from a variable and gets a MALFORMED_QUERY error with status 400. What is wrong, and how do you fix it?
Show answer
The apostrophe in O'Brien ends the string literal early. Escape the single quote with a backslash so the literal reads 'O\'Brien Ltd'. In code, do this with an escaping helper such as soql_quote, which also protects against SOQL injection.