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
sfdcFanBoysfdcFanBoy 

Records Created Last Year, This Month

Hi,

 

 

 

 

I need to get all those records which were created in 'This month of Last Year'.  Since this is November 2012, I need to get all the records created in November last year in SOQL query.  I run this query on the 1st of every month.   Is there any exact date literal ?  Can I compare the months or something like that ?

 

I have checked Data Literals, I found LAST_N_DAYS:n .  I used it to build the following query ( which I do not like it)

 

SELECT Id FROM Account WHERE CreatedDate <= LAST_N_DAYS:365  && CreatedDate >= LAST_N_DAYS:335 

(365-335 =30 days difference, 1 month difference)

 

The query gives incorrect results and is not perfect as the query picks 30 days difference every month which is wrong. If I go with this, I need to calculate for 31 days as well and have to consider leap years and all which is hectic.

 

Any simple Ideas please?

 

Best Answer chosen by Admin (Salesforce Developers) 
Scott_VSScott_VS
Integer year = Date.today().year() - 1;
Integer month = Date.today().month();
List<Account> accnts = [SELECT id FROM Account WHERE CALENDAR_YEAR(CreatedDate) =: year AND CALENDAR_MONTH(CreatedDate) =: month]; 

 

All Answers

Scott_VSScott_VS
Integer year = Date.today().year() - 1;
Integer month = Date.today().month();
List<Account> accnts = [SELECT id FROM Account WHERE CALENDAR_YEAR(CreatedDate) =: year AND CALENDAR_MONTH(CreatedDate) =: month]; 

 

This was selected as the best answer
sfdcFanBoysfdcFanBoy

Thanks Scott.  That works :)

 

 

 

 

Chandra SfdChandra Sfd
Hi, I have the same need of extracting records that were created last year this month. But I would like to use the query in command line data loader. Could you please let me know how can I extract last year this months records using command line data loader? Thank you!