function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Leticia Monteiro Freitas 4Leticia Monteiro Freitas 4 

Database.query with like

Hi, 

I'm trying use a Database.query passing a string and a should use a like with operator '%'+a+'%.

String codeName ;
String query = 'Select ID, Name from Account where codeName like '%' + codeName + '%'.
What is the right syntax? 
See the string codeName is a variable not a literal string. 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Leticia,

Greetings to you!

You can escape new lines, carriage returns, tabs, quotes, and more. The escape character for SOQL is the backslash (\) character.

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_quotedstringescapes.htm

Dynamic SOQL:
String codeName;
String query = 'Select ID, Name from Account where Name like \'%' + codeName + '%\'';
List<Account> accts = database.query(query);
System.debug('List of Account -> ' + accts);

Using Apex Variables:
List<Account> accts = [SELECT Id, Name FROM Account WHERE Name LIKE :('%' + codeName + '%')];
System.debug('List of Account -> ' + accts);

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Ajay K DubediAjay K Dubedi
Hi Leticia,

Modify your Query as given below:
String query = 'Select ID, Name from Account where codeName like ';
String query2 =    '\'%' + String.valueOf(codeName) + '%\'' ;
String finalquery= query+query2;
System.debug(Database.query(finalquery));

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Deepali KulshresthaDeepali Kulshrestha
Hi Leticia,

Try the following code it may be helpful for you:
 
String codeName ='abc';
            String query = 'Select ID, Name from Account where Name like \'%' + codeName  + '%\'';
            List<Account> accList=new List<Account>();
            accList=Database.query(query);
            System.debug('accList--->'+accList);
           
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha