ApexSensei

Drills › SOQL queries

Search names with SOSL

SOQL queries · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A support rep types part of a name into one search box. They expect matching companies first, then matching people, each in A to Z order.

Run one SOSL search across Accounts and Contacts, return the names in a set order, and see why tests need Test.setFixedSearchResults.

What you will learn

SOSL searches text in several objects at once. It returns one list per object, in the order after RETURNING.

List<List<SObject>> hits = [
    FIND :term IN NAME FIELDS
    RETURNING Account(Name), Contact(LastName)
];

Gotcha. SOSL matches whole words. 'Harbor' finds Harbor Alpha, not Harborview. Add trailing * for prefix search; leading * is rejected.

Gotcha. SOSL uses an index that lags saves. Tests find nothing until Test.setFixedSearchResults(ids).

The task

Complete findNames so one SOSL search returns the names of matching Accounts, then the last names of matching Contacts.

Examples:

  • findNames('Harbor') finds Accounts Harbor Beta and Harbor Alpha and a Contact named Maya Harbor → (Harbor Alpha, Harbor Beta, Harbor)
  • findNames('Nobody') finds nothing → an empty list
  • findNames(null), findNames(' ') or findNames(' H ') → an empty list, and no search runs

Requirements:

  1. SOSL needs at least 2 characters. If term is null, blank, or shorter than 2 characters after you trim the spaces, return an empty list (not null) without searching.
  2. Run one SOSL search for the trimmed term IN NAME FIELDS, returning Account Name and Contact LastName.
  3. Sort each object A to Z with ORDER BY inside its part of RETURNING.
  4. Add every Account Name first, then every Contact LastName, and return the list.

Starter code

public class AS_6C2F11FEB11B_NameSearch {
    public static List<String> findNames(String term) {
        List<String> names = new List<String>();
        return names;
    }
}

When it passes

One SOSL search returns Account names A to Z, then Contact last names A to Z. A missing, blank or 1-character term returns an empty list without searching, and a search with no hits returns an empty list.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Filter with date literals