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? – Saumya Ranjan Satapathy Feb 16 '17 at 11:23

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 '17 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 '17 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 ! – Nachiket Deshpande Feb 16 '17 at 11:40
  • You are right, your answer is flexible for such requirement. Question is very much confusing to me! – Raul Feb 16 '17 at 11:42

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.