+ Start a Discussion
Shri RajShri Raj 

BATCH class to Delete records from an Object which are created 10 Days ago from today.

Can anyone share an example considering Account as an example. 

Thanks
Shri
AshlekhAshlekh
Hi,

global class ExampleBatchClass implements Database.Batchable<sObject>{

        global ExampleBatchClass(){
                   // Batch Constructor
        }
       
        // Start Method
        global Database.QueryLocator start(Database.BatchableContext BC){
			Date s = system.today()-10;
			string query = 'select id  from Account where createDdate <:S';
			return Database.getQueryLocator(query);
        }
      
      // Execute Logic
       global void execute(Database.BatchableContext BC, List<Account>scope){
              if(scope.size>0)
		delete scope;
     
       }
     
       global void finish(Database.BatchableContext BC){
            // Logic to be Executed at finish
       }
    }


James LoghryJames Loghry
Exanding on Ashlekh's example, you can use the LAST_N_DAYS:x SOQL function like so:

You can use "Select Id From Account Where CreatedDate <= LAST_N_DAYS:10"

Also, you don't need the "if(scope.size > 0)" check at line 16.  It's superfluous because the DML will only run on non-empty or populated lists.
Todd GillTodd Gill
I realize this is an older thread, but I wanted to respond to the previous comment.  LAST_N_DAYS:10 means "a range of datetimes that includes all of the last ten days" and can be referenced with "=" because it is a range, not a single date.

The previous comment raises a good point that you can use LAST_N_DAYS in queries, but it is incorrect and would actually return all Accounts in the database.  Probably a typo, but in case anyone is using this article in the future, hopefully this helps:
//Returns Id's for all Account records created during the last 10 days
Select Id from Account Where CreatedDate = LAST_N_DAYS:10

//Returns Id's for all Account records created BEFORE the last 10 days
Select Id from Account Where CreatedDate < LAST_N_DAYS:10

//Returns Id's for all Account records in the database: all that were created in the last 10 days AND all that were created before the last ten days
Select Id from Account Where CreatedDate <= LAST_N_DAYS:10