1

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?

1
  • 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
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.

1
  • 2
    Much better answer as it works with other tools such as Data Loader. – Adrian Larson Feb 17 '17 at 11:36
2
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.
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_date_functions.htm

3
  • 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.