2

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

Code:

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

            for(Account account : data)
                {
                    Integer daysCount = (system.today()).daysBetween(Date.valueOf(account.LastModifiedDate));
                    if(daysCount>30){
                        //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];
3
  • 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. Commented Aug 14, 2019 at 15:52
  • 1
    @ThomasTaylor Your > should be <, by the way.
    – sfdcfox
    Commented Aug 14, 2019 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
    Commented Aug 14, 2019 at 15:54

2 Answers 2

11

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.

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

Try this on SOQL and it will work:

SELECT name, Format(LastModifiedDate) FROM Account WHERE LastModifiedDate = LAST_N_DAYS:01

1
  • 1
    How does this help them get records older than 30 days as the question asked when you're filter specifies one day? Commented Jan 17, 2022 at 13:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .