This is my test code

String soqlStr = '1 OR 2 AND 3';

List<String> strList = new List<String>();
strList.add('Name = a');
strList.add('City = b');
strList.add('Birthdate__c = c');
String s2 = '';

for (Integer i = 0; i < strList.size() ; i ++) {

    String s1 = strList[i];
    System.debug(LoggingLevel.INFO, 's1 = ' + s1);

    s2 = soqlStr.replace(String.valueOf(i+1), s1);
    System.debug(LoggingLevel.INFO, 's2 = ' + s2);

I want to get the result:

String soqlStr = 'Name = a OR City = b AND Birthdate__c = c';

enter image description here

  • don't you want Name IN ('a','b','c') ? or why not use apex bind variables?
    – cropredy
    Sep 5, 2019 at 19:26

3 Answers 3


Specifically for your case - Derek's answer is absolutely correct. But in the general case, if we want to build a string by substitution the certain slots with arguments, it is convenient to use String.format() method:

public static String format(String stringToFormat, List<Object> formattingArguments);

Treat the first argument as a pattern and return a string using the second argument for substitution and formatting. The substitution and formatting are the same as apex:outputText and the Java MessageFormat class. Non-string types in the second argument’s List are implicitly converted to strings, respecting the toString() method overrides that exist on the type.

String template = '{0} OR {1} AND {2}';
List<String> params = new List<String>();
params.add('Name = a');
params.add('City = b');
params.add('Birthdate__c = c');
String formattedTemplate = String.format(template, params);
/* String formattedTemplate = 'Name = a OR City = b AND Birthdate__c = c'; */
  • This is a great answer, thank you very much. But I still have a problem, after using [String.format], the last parameter never changes. Result: template2 = City = b OR Birthdate__c = c AND {3}
    – Zhang Ou
    Sep 5, 2019 at 20:24
  • I've updated indexes in my answer, starting from 0. Check again, please. Just a typo Sep 5, 2019 at 20:24
  • I understand, thank you very much.
    – Zhang Ou
    Sep 5, 2019 at 20:25

Looks like you're trying to do things the hard way. SOQL provides a built-in way to do this using IN.


List<String> accountNames = new List<String>{'Tech co', 'MegaCorp, utld.', 'Mom \'n Pop Shop'};
List<Account> accounts = [SELECT Id FROM Account WHERE Name IN :accountNames];

If this is for a dynamic query, you might have to do a little more work, but a little ingenuity with String.join() should get you where you need to go in that case (still using the IN keyword)

  • Sorry, I did not express it clearly. I updated the question, can you help me again?
    – Zhang Ou
    Sep 5, 2019 at 20:03

If you are trying to store a list of conditions and add them to a soql query you can try String.join(strList, ' OR ');.


You must log in to answer this question.

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