Sub topic 2
SOSL or SOQL: choosing the right tool
This chapter assumes you can write basic SOQL (SELECT, WHERE, ORDER BY, LIMIT), read simple Apex, and run anonymous Apex in the Developer Console. It does not cover SOSL syntax yet. The goal is to decide which language fits a requirement before you write any query.
Two languages, two jobs
SOQL (Salesforce Object Query Language) reads records from a database table. You name an object, filter on field values, and get back rows from that object. You can also reach related objects through relationship queries.
SOSL (Salesforce Object Search Language) searches a text index. You give it a search term, and it finds matching words in the text fields of one or many objects. It returns the matches grouped by object.
The difference is in how each one finds data:
- SOQL evaluates your
WHEREconditions against field values. AWHERE Name = 'Acme'condition is an exact comparison. - SOSL looks up words in a search index that the platform builds and maintains. The search is case-insensitive and word-based, and it is built for questions like "where does the word Acme appear anywhere?"
The index has one consequence you should keep in mind. It is updated asynchronously, so a record you just inserted or edited may not appear in SOSL results right away. A SOQL query in the same transaction always sees your DML changes.
What each language can do
| Capability | SOQL | SOSL |
|---|---|---|
| Objects per query | One primary object, plus related objects through relationships | Several unrelated objects in one query |
| Field types searched or filtered | All types: number, date, checkbox, lookup, text, and others | Text-based fields only: text, text area, email, phone, and URL |
| Matching style | Exact comparison, ranges, `LIKE` patterns | Word and phrase matching against an index, with wildcards |
| Aggregates (`COUNT`, `SUM`, `GROUP BY`) | Yes | No |
| Subqueries and relationship queries | Yes | No |
| Result shape in Apex | `List<SObject>` | `List<List<SObject>>`, one inner list per object |
| Freshness | Sees changes immediately | Index may lag behind recent changes |
| Apex query limit per transaction | 100 synchronous, 200 asynchronous | 20 |
| Rows returned per query | Up to 50,000 per transaction in total | Up to 2,000 per query |
The last two rows matter for design. SOSL has a much smaller budget, so it suits a user-facing search box and not a bulk data process.
Decision criteria
Start with what you know about the data you want.
Choose SOQL when
- You know which object holds the data.
- You filter on non-text fields such as dates, amounts, picklist values, checkboxes, or record IDs.
- You need aggregates, grouping, or subqueries.
- You need every matching row, not the first 2,000.
- You must see records inserted or updated earlier in the same transaction. Trigger and batch logic usually falls here.
Choose SOSL when
- You do not know which object or field contains the text. A global search box is the standard case.
- You want to search several objects at once and show grouped results.
- You are matching words inside long text, such as descriptions or notes.
- You want fast text lookup on a large table. A SOQL
LIKE '%term%'with a leading wildcard cannot use a standard index, so on a large object it scans many rows and risks a "non-selective query" error. The SOSL index is built for this kind of lookup.
A hybrid is often best
The two languages combine well. Use SOSL to find candidate records across objects, then use SOQL to do exact work on those IDs. SOSL can't aggregate, so this is how you get totals for the records a user found.
The same task in both languages
Suppose a user types Acme and you want matching accounts. This is the SOQL version:
String term = 'Acme';
String pattern = '%' + term + '%';
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Name LIKE :pattern
];
System.debug('SOQL found ' + accounts.size() + ' accounts');This is the SOSL version:
String term = 'Acme';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name)
];
List<Account> accounts = (List<Account>) results[0];
System.debug('SOSL found ' + accounts.size() + ' accounts');For one object they look similar, but they behave differently:
- The
LIKEquery matches the charactersAcmeanywhere in the name, including inside a longer word. - The SOSL query matches the word
Acmein the index. A name such asAcme Corpis found, butPacmenis not. You would writeAcme*to match words that start with it. - Adding a second object to the SOQL version needs a second query and a second limit count. In the SOSL version it only needs another entry in
RETURNING, and it still counts as one query.
The next chapters cover the SOSL syntax used here. For now, notice that the result is a list of lists, with results[0] holding the first object named in RETURNING.
A SOSL-then-SOQL pattern
This script finds contacts that mention a term anywhere, then totals opportunity amounts for their accounts. SOSL alone can't produce the totals.
String term = 'renewal';
List<List<SObject>> hits = [
FIND :term IN ALL FIELDS
RETURNING Contact(Id, AccountId)
];
Set<Id> accountIds = new Set<Id>();
for (Contact c : (List<Contact>) hits[0]) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<AggregateResult> totals = [
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE AccountId IN :accountIds
GROUP BY AccountId
];
for (AggregateResult ar : totals) {
System.debug(ar.get('AccountId') + ' total: ' + ar.get('total'));
}The script spends one SOSL query and one SOQL query. The SOQL step is exact and complete for the IDs it receives, but the SOSL step is capped at 2,000 rows and depends on the index.
Edge cases and common mistakes
- Using SOSL to check for existence right after an insert. The index may not have caught up, so the record can be missing. Use SOQL by ID or by a field value when you need certainty inside a transaction.
- Using SOSL for non-text conditions. You can't search a number or date field with a
FINDterm. Filter those with a per-objectWHEREinRETURNING, or use SOQL. - Treating the 2,000-row cap as a page size. SOSL is for relevance-ranked results, not for exporting data. If you need every record that matches a condition, use SOQL.
- Running SOSL in a loop. The limit of 20 SOSL queries per transaction is much easier to hit than the SOQL limit. Search once, with several objects in
RETURNING, and process the lists. - Assuming a leading-wildcard
LIKEis as good as a search. It works on small objects, then fails with a non-selective query error as the data grows. - Forgetting that tests see no search results. SOSL in a test method returns nothing for new records unless you set fixed results. A later chapter shows how.
Summary of the decision
- Unknown object or field, text input, several objects: SOSL.
- Known object, typed fields, exact conditions, aggregates, or full result sets: SOQL.
- A text search that needs exact follow-up work: SOSL first, then SOQL on the IDs.
Exercise
A support portal has one search box. A user types a customer's last name, and the page must show matching Contacts, Cases, and Accounts together. A nightly job, separate from the portal, must list every Opportunity with an Amount above 100,000 closing this quarter. Which language fits each requirement, and why?
Show answer
Use SOSL for the portal search. The object and field are unknown, the input is a word, and the page needs results grouped across three objects in one query. Use SOQL for the nightly job. It filters on a number field and a date field, which SOSL cannot search, and it needs every matching row, while SOSL returns at most 2,000 per query.
Exercise
A trigger inserts an Account and then runs a SOSL query for that account's name in the same transaction. The query returns no rows. What is the likely cause, and what should the trigger use instead?
Show answer
The search index is updated asynchronously, so the new record is not yet searchable. The trigger should query the record with SOQL, for example by its ID, because SOQL sees changes made earlier in the same transaction.