+ Start a Discussion
paul-lmipaul-lmi 

Using Apex variables with LIKE in SOQL queries

I thought I'd share since figuring this out was kind of crappy.  Since you can't (or I couldn't find how) concatenate a string in an SOQL query to combine wildcards like % and _ to make a query, you need to do so with the variable you want to pass in.

 

So if you want to do an SOQL query using LIKE, wild cards, and an Apex variable, this will work.

 

//create a string
String s = 'mystring';

//add wildcards around it to be more flexible in the search
s = '%' + s + '%';

//create an SOBject list with the results from our query
SObject[] obj = [select id from SObjectName where Name LIKE :s];

 

and this will return any row from the SObjectName where the "Name" field has "mystring" in it.

Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert

You could use Dynamic Apex to dynamically build the SOQL string during runtime.

 

 

All Answers

aalbertaalbert

You could use Dynamic Apex to dynamically build the SOQL string during runtime.

 

 

This was selected as the best answer
paul-lmipaul-lmi

so something like this?

 

//create a string
String s = 'mystring';

//create an SOBject list with the results from our query
SObject[] obj = Database.query('SELECT Id FROM SObjectName WHERE Name LIKE' + '%' + s + '%');

 

 

Message Edited by paul-lmi on 05-14-2009 01:13 PM
aalbertaalbert

Yes, correct. Here is a little extra to cast the SObject to an Account (for example)

 

 

//create a string String s = 'mystring'; //create an SOBject list with the results from our query List<SObject> obj= Database.query('SELECT Id FROM SObjectName WHERE Name LIKE' + '%' + s + '%'); for(SObject o : obj){ Account a = (Account)o; //do more here.....

}

 

 

 

paul-lmipaul-lmi

i was using SObject so as to be generic for this question.  realistically, i don't think i'd personally need to make the code that generic, rather than just calling the proper SOBject type when creating "obj" in the first place.

 

thanks much for explaining this.

nitish_161nitish_161

thanks ... ur solution really helped me . :)

Deepak@UXLTDeepak@UXLT

Thanks Paul. Your soution helped me

Team WorksTeam Works
Hello Guys

Again Stuck with the concatenation :

private final String SOQL_RECENT_REC = 'SELECT LastViewedDate,Type,UserRoleId FROM RecentlyViewed';
private final String CONDITION_USER_SORT = ' Order By LastViewedDate DESC LIMIT 20';
List<RecentlyViewed> recentViewed= new List<RecentlyViewed>();
recentViewed = Database.query(SOQL_RECENT_REC +' WHERE Type = \'Account \' ' + CONDITION_USER_SORT);

Should run a query like the following :
recentViewed = [SELECT LastViewedDate,Type,UserRoleId FROM RecentlyViewed Where Type='Account' Order By LastViewedDate DESC LIMIT 20];

Many Thanks !!