I am trying to delete records from last one year created records using a batch class. How can I query record whose CreatedDate spans from the current date to last one year?

  • What is the boundary of the last one year? does it mean records created in 2016 only or from 16thFeb2016 to 16thFeb2017? Feb 16, 2017 at 11:23

3 Answers 3


You can use Date Literals:

For deleting records of last year:

delete [SELECT Id FROM Opportunity WHERE CreatedDate = LAST_YEAR];

For all records not created this year:

delete [SELECT Id FROM Opportunity WHERE CreatedDate != THIS_YEAR];

With this, you do not have to worry about manipulating with date/year separately.

  • 2
    Much better answer as it works with other tools such as Data Loader.
    – Adrian Larson
    Feb 17, 2017 at 11:36
Integer year = Date.today().year() - 1;
Date todaysDate = Date.today();
List<Contact> contactList= [SELECT id FROM Contact WHERE CALENDAR_YEAR(CreatedDate) =: year AND DAY_ONLY(CreatedDate) =: todaysDate];

refer these date time functions and mold the SOQL query as per your requirment.

  • Using date literals is much better :)
    – Raul
    Feb 16, 2017 at 11:38
  • question says that user321 want the records from current date to last year, (how to query current date to last one year created date records using soql query) yeah date literals are also advisable ! Feb 16, 2017 at 11:40
  • You are right, your answer is flexible for such requirement. Question is very much confusing to me!
    – Raul
    Feb 16, 2017 at 11:42

You can also tray a much yeasier way to do it

Date todaysDate = Date.today();
Date lastYearDate = Date.today() - 365;
List <Account> accts = [SELECT Id, CreatedDate__c
                        FROM Account 
                        WHERE CreatedDate__c >: lastYearDate AND CreatedDate__c <: todaysDate 

You must log in to answer this question.

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