2

I have this query Select Id, Email, ContactId, Username from User where Username Like '\_%' works perfectly with Devloper console and give me users whose username starts with _

I am using this code in apex, but there its not giving the desired result.

From salesforce docs

The LIKE operator in SOQL and SOSL supports escaping of special characters % or _. Don’t use the backslash character in a search except to escape a special character.

PS : I have tried escaping double backslash \\_ , four backslash \\\\_, [_] . None worked. and not escaping also.

2
  • Have you tried NOT escaping it? Sep 8, 2016 at 7:43
  • yes, Then it gives all users.
    – Ankuli
    Sep 8, 2016 at 7:52

2 Answers 2

6

In my tests, a double backslash escape has provided the desired results:

List<User> users = (List<User>)Database.query('Select Id, Email, ContactId, Username  from User where Username Like \'\\_%\'');
3
  • 2
    How about static SOQL?
    – Keith C
    Sep 8, 2016 at 8:31
  • This worked. But I am wondering, how n why. same using normal soql not working. wt does Database.query method made the difference.
    – Ankuli
    Sep 8, 2016 at 9:17
  • what about this [Select Id, Email, ContactId, Username from User where (Email IN: setEmailIds OR ContactId IN: lstNewContact) AND (NOT Username Like '\_%')]
    – Ankuli
    Sep 8, 2016 at 9:23
4

I am adding answer here using normal SOQL also

Working

 String strLike = '\\_%';
    system.debug([Select Id, Email, ContactId, Username  from User where Username  Like :strLike ]);

as well using dynamic query

List<User> users = (List<User>)Database.query('Select Id, Email, ContactId, Username  from User where Username Like \'\\_%\'');

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .