Sub topic 3
Querying data with SOQL and SOSL
This chapter assumes you know HTTP and JSON basics, understand Salesforce objects, fields, and records, and can read SQL-style queries. Every Salesforce data API that reads records relies on one of two query languages. SOQL (Salesforce Object Query Language) retrieves records from one object and the objects related to it. SOSL (Salesforce Object Search Language) searches text across many objects at once. Later chapters on the REST API, Bulk API 2.0, and Apex REST all take these queries as input, so you need to know how they behave.
SOQL basics
SOQL looks like SQL, with some differences. You always query a named object, you list fields explicitly, and there is no SELECT *. There are also no joins. You follow relationships that are already defined between objects.
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
WHERE Industry = 'Technology' AND AnnualRevenue > 1000000
ORDER BY AnnualRevenue DESC
LIMIT 10The main clauses are:
SELECTlists the fields to return.FROMnames exactly one object.WHEREfilters rows. String values use single quotes. Dates and numbers do not use quotes.ORDER BYsorts the results. AddNULLS LASTif you need null values at the end.LIMITcaps the number of rows returned.OFFSETskips rows. It is limited, so avoid it for deep paging.
SOQL supports LIKE with % and _ wildcards, IN lists, and date literals such as LAST_N_DAYS:30 and THIS_FISCAL_QUARTER. Date literals are handy because the server computes them, so your client does not have to format dates.
SELECT Id, Name, CreatedDate
FROM Opportunity
WHERE CloseDate = NEXT_N_DAYS:14
AND StageName IN ('Prospecting', 'Negotiation/Review')Relationship queries
Because SOQL has no join keyword, relationships do the work of joins. There are two directions.
A child-to-parent query uses dot notation on the relationship name. For a standard lookup, the relationship name is the field name without Id. For a custom lookup, the name ends in __r.
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Technology'A parent-to-child query uses a subquery on the child relationship name, which is usually the plural of the child object, such as Contacts.
SELECT Id, Name,
(SELECT Id, LastName, Email FROM Contacts WHERE Email != null)
FROM Account
WHERE Industry = 'Technology'The JSON response nests the child rows inside each parent, under Contacts.records. Clients must handle this nesting. A nested subquery can also be paged on its own, so a parent with many children may return a nextRecordsUrl inside the child block.
A semi-join filters one object by the existence of related records in another:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won')Relationship traversal is limited to five levels from child to parent and one level from parent to child in a subquery. Real limits can differ by API version, so check the SOQL documentation for the version you target.
Aggregates and grouping
SOQL supports COUNT(), SUM(), AVG(), MIN(), and MAX() with GROUP BY and HAVING.
SELECT StageName, COUNT(Id) deals, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = true
GROUP BY StageName
HAVING SUM(Amount) > 100000Aggregate results use aliases such as deals. If you leave out an alias, Salesforce names the columns expr0, expr1, and so on. This is a common surprise when you parse the JSON. Aggregate queries also cannot be returned in the same pageable way as plain queries in every context, so keep result sizes small by grouping.
Running SOQL through the REST API
The REST API exposes SOQL at the /query resource. The query goes in the q parameter and must be URL-encoded. The --data-urlencode flag in curl does this for you.
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/query" \
--data-urlencode "q=SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 5" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response is JSON with three key fields:
| Field | Meaning |
|---|---|
| `totalSize` | Total number of rows the query matches |
| `done` | `true` when there are no more pages |
| `nextRecordsUrl` | Relative URL to fetch the next page, present only when `done` is `false` |
By default, a query returns up to 2,000 records per page. To read more, keep requesting nextRecordsUrl until done is true. Do not build the next URL yourself, because it carries a server-side cursor.
curl "https://MyDomain.my.salesforce.com$NEXT_RECORDS_URL" \
-H "Authorization: Bearer $ACCESS_TOKEN"The /queryAll resource works the same way but also returns soft-deleted and archived records. You can check IsDeleted to tell them apart.
sequenceDiagramThe diagram below shows the paging loop.
Writing selective queries
On large objects, query performance depends on selectivity. A selective query uses a filter that lets Salesforce use an index, so it does not scan the whole table. Indexed fields include Id, Name, OwnerId, CreatedDate, SystemModstamp, lookup and master-detail fields, and fields marked as External ID or unique. Salesforce Support can add custom indexes on request.
Habits that hurt selectivity:
- Filtering with a leading wildcard, such as
LIKE '%corp'. - Using negative operators such as
!=orNOT INas the only filter. - Wrapping an indexed field in a function.
- Filtering on a field that matches a large share of the rows.
Selectivity matters most for queries run from triggers or on objects with very many records, where a non-selective query can fail with an error instead of just running slowly. For integration jobs that must read an entire large object, a plain query is the wrong tool. Bulk API 2.0, covered in a later chapter, is built for that.
Two more practical rules apply. Select only the fields you need, because every extra field adds payload size and processing time. Filter on SystemModstamp or LastModifiedDate for incremental syncs, so each run reads only changes since the last run.
SOQL injection
Never build a query by concatenating untrusted input. A value containing a quote can change the meaning of the query. In Apex, use bind variables, which are safe:
String industry = 'Technology';
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = :industry];When you must build dynamic SOQL in Apex, use Database.queryWithBinds or String.escapeSingleQuotes(). From an external client, escape or validate values before you add them to the q parameter.
SOSL: searching across objects
SOSL searches text fields across several objects in one request. Use it when you do not know which object holds the value, or when you want fast keyword matching. The basic form is:
FIND {Acme} IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, LastName, Email), Lead(Id, Company)The parts are:
FIND {term}is the search text. Wildcards*and?are allowed.IN ... FIELDSlimits the search to name, email, phone, sidebar, or all fields. The default is all fields.RETURNINGlists the objects and the fields to return, and may include its ownWHERE,ORDER BY, andLIMITper object.
Over REST, SOSL uses the /search resource, with the query in the q parameter.
curl -G "https://MyDomain.my.salesforce.com/services/data/v60.0/search" \
--data-urlencode "q=FIND {Acme} IN NAME FIELDS RETURNING Account(Id, Name), Contact(Id, LastName)" \
-H "Authorization: Bearer $ACCESS_TOKEN"SOSL results come from a search index, so a newly created record may take a short time to appear. SOSL also returns at most 2,000 rows in total across all the objects listed, and it has no paging through nextRecordsUrl. Use it for finding records, not for extracting data.
Choosing between SOQL and SOSL
| Question | SOQL | SOSL |
|---|---|---|
| Objects searched | One, plus related objects | Many at once |
| Matching style | Exact, range, and pattern filters | Tokenized text search |
| Results | Rows with paging | Up to 2,000 rows, no paging |
| Aggregates and grouping | Yes | No |
| Data freshness | Immediate | Depends on the search index |
| Best for | Retrieving and syncing records | Finding records by keyword |
Common errors
MALFORMED_QUERYusually means a typo, a missing quote, or a field name that does not exist on the object.INVALID_FIELDmeans the field name is wrong, or the user's field-level security hides it. API calls respect the permissions of the authenticated user, so two users can get different results from the same query.QUERY_TIMEOUTmeans the query was not selective enough. Add an indexed filter.URI too longappears when a long query in a GET URL exceeds the length limit. Shorten the query, or send it through a different resource.- Nothing returned, no error, often means sharing rules hide the records from the integration user.
Exercise
An integration runs every hour and must pick up Accounts changed since the previous run, along with each account's contacts. Write the SOQL query, and say which pattern you use to read all pages of the result.
Show answer
SELECT Id, Name, SystemModstamp, (SELECT Id, LastName FROM Contacts) FROM Account WHERE SystemModstamp > 2026-12-01T07:00:00Z ORDER BY SystemModstamp. The date literal is the time of the previous run, which the integration stores. Filtering on SystemModstamp uses an index and limits the rows to recent changes. The parent-to-child subquery returns contacts nested under each account. To read all pages, call /query, then keep following nextRecordsUrl until done is true.
Exercise
A support agent types "Acme" and you do not know whether it is an account, a contact, or a lead. Which language fits, and what is one limit of it?
Show answer
SOSL, because it searches several objects in one request, for example FIND {Acme} RETURNING Account(Id, Name), Contact(Id, LastName), Lead(Id, Company). A limit is that it returns at most 2,000 rows in total and offers no paging, so it cannot be used to extract a full data set.