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
Ramana VRamana V 

SOQL query to retrieve records not more than 2 years

Hi All,
I want retrieve case records which from today to 2 years ago exactly. I have tried by using Last_N_DAYS:730. but it is giving even 2016 and before records also. I want only records between today and two years. Not before two years.
Can some please help me with SOQL query

Thanks in Advance!!

Regards,
Ramana
Best Answer chosen by Ramana V
Shashidhar NaruShashidhar Naru
Hi Ramana
You can try this
select id, createdDate from case where CreatedDate = LAST_N_Days:730 AND CreatedDate < LAST_N_Days:1

All Answers

Ramana VRamana V
Hi Divya 
I am using like this
select id, createdDate from case where createdDate < LAST_N_DAYS:730
Sunil RathoreSunil Rathore
Hi Ramana,

Greetings to you!

You want to retrieve records that are created 2 years ago and after that. In your query, you are using createdDate < LAST_N_DAYS:730 which will give you record created before 730 days. To retrieve record created after 730 days use the below query:
select id, createdDate from case where createdDate > LAST_N_DAYS:730

Or instead of using days you can use LAST_N_YEARS:n.  Refer the below query:
select id, createdDate from case where createdDate > LAST_N_YEARS:2

Hope this will help you. If does then mark it as the best answer so it can also help others in the future.

Many Thanks,
Sunil Rathore
Ajay K DubediAjay K Dubedi
Hi Ramana,

I think you should not go with the Last_N_Days:730 as there may be a problem during leap years and non-leap years. The better option is directly used years in your query like below:

     Select Id FROM Case WHERE CreatedDate > LAST_N_YEARS:2

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com 
Ramana VRamana V
Hi Sunil / Ajay
Thanks for your reply
The query what you provided is giving records even 2 years older. I want records exactly 2 years only
 
Shashidhar NaruShashidhar Naru
Hi Ramana
You can try this
select id, createdDate from case where CreatedDate = LAST_N_Days:730 AND CreatedDate < LAST_N_Days:1
This was selected as the best answer