1

I have a question, how to delete all records except newly created 1000 records(For Eg: in a Account Object i have 11000 records,in that 1000 records are created in this month, now all 10000 records should be delete,except recently created 1000 records.) by using batch class.

global class Deletecc implements DataBase.Batchable<sObject>
{
    global DataBase.QueryLocator start(DataBase.BatchableContext bc)
    {
        return DataBase.getQueryLocator([SELECT Id,Name FROM Credit_Card__c LIMIT 1000]);
    }
    global void execute(DataBase.BatchableContext bc,List<Credit_Card__c> ListTli)
    {
        List<Credit_Card__c> ListTarget = new List<Credit_Card__c>();
        //List<Credit_Card__c> ListTarget1000 = new List<Credit_Card__c>();
        for(Credit_Card__c t : ListTli)
        {
            if(t.Name!=null) 
            {
                ListTarget.add(t);
                system.debug('-->>'+ListTarget);
            }
         } 
        if(ListTarget.size()>0)
        {
            delete ListTarget;
        }
    }
    global void finish(DataBase.BatchableContext bc)
    {

    }
}
  • did you try to write SOQL for this requirement? – Santanu Boral May 22 '17 at 15:06
  • yes Santanu Boral, l have used LIMIT as my filter,but how to find the count of new records ? – user44771 May 22 '17 at 15:10
  • can you post your code whatever you have tried so far – Santanu Boral May 22 '17 at 15:10
  • @SantanuBoral see the code which i have tried,but its a standard delete batch class, i need help in Soql Query – user44771 May 22 '17 at 15:15
  • You don't need to use the global modifier... – Adrian Larson May 22 '17 at 15:16
4

If you want to skip the newest 1000 records, use an OFFSET clause. Make sure you add an ORDER BY clause as well so that the newest records are those skipped. Since you can't use OFFSET in your query locator, you'll have to query down the 1000th record and use its CreatedDate in your filter:

MyObject__c thresholdRecord = [
    SELECT Id FROM MyObject__c
    ORDER BY CreatedDate DESC
    LIMIT 1 OFFSET 1000
];
return Database.getQueryLocator([
    SELECT Id FROM MyObject__c
    WHERE CreatedDate <= :thresholdRecord.CreatedDate
]);
  • I have used OFFSET But i am Getting this error: FATAL_ERROR|System.UnexpectedException: SOQL OFFSET clause is not supported in Batch Apex. – user44771 May 22 '17 at 15:41
1

Using trigger or execute anonymous window

Datetime d = datetime.now().addmonth(1)
List <account> a = list <account>();
a = [select id,name from account where created date >: d limit1000];
Delete a;
  • 1
    How is this answer even related to the question? This doesn't get you the newest records, and can't ever even return data, since CreatedDate is the field's API Name and it will never have a value in the future. – Adrian Larson May 22 '17 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy