LearnFrenzy
Sign in Take a free test

sObjects, SOQL and SOSL · Lesson 18 of 41

SOSL: Searching Across Objects in Apex

5 min read Updated Nov 8, 2026 Saurabh Samir

SOQL asks "give me records of this object that match these conditions". SOSL (Salesforce Object Search Language) asks "where does this text appear?" – across many objects and fields at once, using the same search index as the global search bar. It's the right tool for search boxes and "find anything about Acme" features.

In this lesson

  • FIND, IN and RETURNING
  • Reading the results
  • The search index and timing
  • Testing SOSL with fixed results
  • SOSL vs SOQL

The anatomy of a SOSL query

String term = 'acme*';
List<List<SObject>> results = [
    FIND :term IN ALL FIELDS
    RETURNING Account(Id, Name, Industry WHERE Industry != null ORDER BY Name LIMIT 10),
              Contact(FirstName, LastName, Email),
              Opportunity(Name, Amount WHERE IsClosed = false)
    LIMIT 50
];

List<Account> accounts = (List<Account>) results[0];          // same order as RETURNING
List<Contact> contacts = (List<Contact>) results[1];
List<Opportunity> opportunities = (List<Opportunity>) results[2];
  • FIND takes the search text: words, * and ? wildcards, quotes for phrases, AND/OR/AND NOT.
  • IN chooses the field group: ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS.
  • RETURNING lists objects and the fields to return, each with optional WHERE, ORDER BY and LIMIT.
  • The result is a List<List<SObject>> – one inner list per object, in RETURNING order.

The search index isn't instant

SOSL doesn't scan tables; it uses a search index that's updated asynchronously. A record inserted a moment ago usually won't be found yet – typically it appears within seconds to minutes. That has two consequences: don't insert-then-search in the same transaction, and in tests SOSL returns nothing unless you tell it what to return.

Testing SOSL with fixed results

Test.setFixedSearchResults defines which record Ids the next SOSL query returns in a test. The WHERE clauses in RETURNING still apply to those records:

// CustomerSearch.cls
public with sharing class CustomerSearch {
    public class Result {
        public List<Account> accounts;
        public List<Contact> contacts;
    }

    public static Result search(String text) {
        Result r = new Result();
        if (String.isBlank(text) || text.trim().length() < 2) {
            r.accounts = new List<Account>();
            r.contacts = new List<Contact>();
            return r;
        }
        List<List<SObject>> found = [
            FIND :text IN ALL FIELDS
            RETURNING Account(Name, Industry ORDER BY Name), Contact(FirstName, LastName, Email ORDER BY LastName)
            LIMIT 20
        ];
        r.accounts = (List<Account>) found[0];
        r.contacts = (List<Contact>) found[1];
        return r;
    }
}
// CustomerSearchTest.cls
@IsTest
private class CustomerSearchTest {
    @IsTest
    static void findsAccountsAndContacts() {
        Account acme = new Account(Name = 'Acme Corp', Industry = 'Energy');
        insert acme;
        Contact asha = new Contact(FirstName = 'Asha', LastName = 'Verma', Email = 'asha@acme.example', AccountId = acme.Id);
        insert asha;

        Test.setFixedSearchResults(new List<Id>{ acme.Id, asha.Id });   // what the index "finds"
        CustomerSearch.Result r = CustomerSearch.search('acme');

        Assert.areEqual(1, r.accounts.size(), 'one account');
        Assert.areEqual('Acme Corp', r.accounts[0].Name);
        Assert.areEqual(1, r.contacts.size(), 'one contact');
    }

    @IsTest
    static void ignoresVeryShortTerms() {
        CustomerSearch.Result r = CustomerSearch.search('a');
        Assert.isTrue(r.accounts.isEmpty() && r.contacts.isEmpty(), 'no search for one letter');
    }

    @IsTest
    static void returnsNothingWithoutFixedResults() {
        insert new Account(Name = 'Globex');
        CustomerSearch.Result r = CustomerSearch.search('globex');
        Assert.areEqual(0, r.accounts.size(), 'SOSL in tests is empty unless results are fixed');
    }
}

Test run

✓ CustomerSearchTest.findsAccountsAndContacts
✓ CustomerSearchTest.ignoresVeryShortTerms
✓ CustomerSearchTest.returnsNothingWithoutFixedResults

Tests: 3 passed, 0 failed, 3 total

The third test documents the behaviour explicitly: inserting a record and searching for it in a test finds nothing. If your search code has a minimum length rule (as here), always validate input before searching – a SOSL search term needs at least two characters anyway.

SOSL vs SOQL

Use SOQL when…Use SOSL when…
you know the object and field to filter onyou're searching text and don't know where it is
you need exact matches, ranges, relationships, aggregatesyou need to search several objects at once
data must reflect changes made a moment agoa short indexing delay is acceptable
you need up to 50,000 rowsa few hundred best matches are enough (max 2,000 rows)

A search box over Accounts and Contacts? SOSL. "All open cases for this account"? SOQL. Each SOSL query counts against a separate limit of 20 per transaction.

Practice

Try it yourself

  1. Write a SOSL query that searches only email fields for 'globex.example' and returns Contacts and Leads.

    Show answer

    [FIND 'globex.example' IN EMAIL FIELDS RETURNING Contact(Name, Email), Lead(Name, Email)]

  2. A test inserts an Account and then calls your SOSL search, but the assertion "found 1 account" fails. What's missing?

    Show answer

    Test.setFixedSearchResults(new List<Id>{ acc.Id }) before the search – SOSL returns nothing in tests otherwise.

Quick check

What type does a SOSL query return?

List<List<SObject>> – one list per RETURNING object.

Will a record inserted in the same transaction be found by SOSL?

Usually not – the search index updates asynchronously.

How many SOSL queries are allowed per transaction?

20.

Summary

  • SOSL searches text across objects: FIND … IN … RETURNING ….
  • Results come back as one list per object, in RETURNING order.
  • The search index is asynchronous; in tests, use Test.setFixedSearchResults.
  • Use SOQL for precise filters and relationships, SOSL for text search.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links