I can't understand the purpose of putting asterisks before and after the SOSL query below. Is it to cover searches for the wildcards just Jsmith when the user searches smith or smithj when the user searches smith?

searchquery = 'FIND\'' + '*' + conLN + '*' + '\' IN ALL FIELDS RETURNING Contact(Name, Id, FirstName, LastName  ORDER BY Createddate DESC)';

Where conLN is a string last name passed in from an input. The string is escaped to prevent single quote errors.

The documentation tends to indicated wildcards: https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_sosl_find.htm

The reason I ask is because I believe some part of this is interfering with quote searches: Ex: O'Connor.


Wildcards at the beginning of a search term are not supported. This can definitely cause you to get incorrect results, so don't do it. Wildcards at the end are acceptable, but will return more (less accurate) results than not adding it.

If I were you, I'd just pass in the values verbatim. Also, since you're not actually doing dynamic searching, consider converting to an inline query instead:

Contact[] searchresults = [FIND :conLN IN ALL FIELDS RETURNING Contact(Name, Id, FirstName, LastName  ORDER BY Createddate DESC)];

For names like O'Connor, though, the quote needs to be escaped to work correctly: Oconnor and O\'Connor will return results, but O'Connor will not. You may want to call String.escapeSingleQuotes to make sure you get the desired behavior.

| improve this answer | |
  • Thank you! Works like a charm. Can you think of any logical reason why the initial developer would have placed wildcards in the beginning and end of this query? – S.B. Apr 5 '18 at 20:46
  • 1
    @S.M. Probably because they come from other programming background and assumes Salesforce search is the same. There's no logical reason why any search should start with a wildcard in Salesforce. – sfdcfox Apr 5 '18 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.