0

Is it possible to construct a SOQL query with a list literal in the WHERE clause?

I have this query:

bookings = [SELECT Asset__c A, Asset__r.Name An FROM Booking__c WHERE 
                ((Date_begin__c IN (2017-08-10, 2017-08-16, 2017-08-25,2017-08-29, 2017-08-21, 2017-08-23)) OR 
                 (Date_end__c IN (2017-08-16, 2017-08-17, 2017-08-29, 2017-08-22, 2017-08-26, 2017-08-27))) GROUP BY Asset__c, Asset__r.Name];

I don't want use the dates in hard code like your see in this example.

I have the dates on other list

DateBeginList = new List<Date>(); 
/* examble  */
DateBeginList = (2017-08-21 00:00:00, 2017-08-29 00:00:00, 2017-08-23 00:00:00, 2017-08-10 00:00:00)

Is this possible?

  • Please refrain from using all caps. – Adrian Larson Aug 22 '17 at 17:18
  • When an answer addresses your problem, please consider accepting it by clicking on the check mark/tick to the left of the answer, turning it green. This marks the question as resolved to your satisfaction, and awards reputation both to you and the person who answered. If you have >= 15 reputation points, you may also upvote the answer if you wish. There is no obligation to do either. – Adrian Larson Aug 23 '17 at 4:07
3

Yes, you can do this through variable binding:

Date[] startDates = new Date[] { Date.newInstance(2017, 8, 21), Date.newInstance(... };
bookings = [SELECT ... FROM ... WHERE Date_Begin__c IN :startDates ...];

You can read more about it in Using Apex Variables in SOQL and SOSL Queries.

| improve this answer | |
  • And if you are like me and are coming from the SQL world note that this won't work: WHERE Date_Begin__c IN (:startDates) with parens... – Shane Apr 26 '19 at 18:15
  • 1
    @Shane This works: String hello = 'hello', world = 'world'; Account[] records = [select id from account where name in (:hello, :world)]; Parentheses can be used for single values, but not for collections. You can use either or, but not both at the same time. – sfdcfox Apr 26 '19 at 18:21

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.