I wrote the code for the condition: delete data where LastModifiedDate is older than 30days from today.


data= [SELECT Id, Name, Type, Status, LastModifiedDate FROM Account ];

            for(Account account : data)
                    Integer daysCount = (system.today()).daysBetween(Date.valueOf(account.LastModifiedDate));
                        //Purge data
                        delete account ;

But should write above logic in the SOQL query itself to get data which is older than 30days from now to delete. I tried with the below SOQL but it gives all records even latest records too.

  data = [SELECT Id, LastModifiedDate FROM Accont where  LastModifiedDate = LAST_N_DAYS: 30];
  • If you want data last modified more than 30 days ago, you need WHERE LastModifiedDate > LAST_N_DAYS:30. What you have there, WHERE LastModifiedDate = LAST_N_DAYS:30 shouldn't get all records, but only those modified within the last 30 days. – Thomas Taylor Aug 14 '19 at 15:52
  • 1
    @ThomasTaylor Your > should be <, by the way. – sfdcfox Aug 14 '19 at 15:54
  • when I gave "LastModifiedDate > LAST_N_DAYS:30" or "LastModifiedDate < LAST_N_DAYS:30", it returns empty records even I have data. – RKCY Aug 14 '19 at 15:54

You can use a filter without needing a variable, via LAST_N_DAYS:

data = [SELECT LastModifiedDate 
        FROM Account 
        WHERE LastModifiedDate < LAST_N_DAYS:30];

This returns records that haven't been modified in 30 days.

Also see Date Formats and Date Literals for other alternatives.

| improve this answer | |
  • The above query giving empty records. – RKCY Aug 14 '19 at 15:59
  • @RKCY If so, then there aren't any such records. – sfdcfox Aug 14 '19 at 16:02
  • @sfdcfox- Yes, I had verified in another account..This above query works great. Thanks. – RKCY Aug 14 '19 at 16:15

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.