0

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.

  • Have you tried NOT escaping it? – Fernando Gavinho Sep 8 '16 at 7:43
  • yes, Then it gives all users. – Ankuli Sep 8 '16 at 7:52
4

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 \'\\_%\'');
  • 2
    How about static SOQL? – Keith C Sep 8 '16 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 '16 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 '16 at 9:23
2

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 \'\\_%\'');

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.