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
PreyankaPreyanka 

Fetch Data from object between different date range in single query

I need to query a Custom object that has a relationship with Account (Account is Parent). 
I have a requirement where I need to fetch all data from custom object where the set of Id will be of Account, and for each account the dateframe is different for each custom object.

EG: For Account 1 I have to fetch all data from custom object where the created date is within 10/03/2019 to 20/03/2019
For Account 2 I have to fetch all data from custom object where the created date is within 18/02/2019 to 25/02/2019 

There can be many account and different date range.

So I have taken this solution, put all the account Id in one set and calculate the greatest and oldest date from all date timeframe then fetch the data from custom object then again using for loop get the exact data that is needed.

Is there any better solution to do this other than mentioned above. Please provide the details.

Thanks
Preyanka

 
Deepali KulshresthaDeepali Kulshrestha
Hi Preyanka,

You can do this in a single query.
-first you have to make the instance of the dates.

Date d1 = Date.newInstance(2019,3,10);
Date d4 = Date.newInstance(2019,3,20);
Date d2 = Date.newInstance(2019,2,18);
Date d3 = Date.newInstance(2019,2,25);
-here is your query:-
List<Account> acc=[select Id from Account where (CreatedDate >=: d1 AND CreatedDate <=: d2) OR (CreatedDate >=: d3 AND CreatedDate <=: d4) LIMIT 10000];

-Please check the condition of greater than and less than according to your need.

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