Salesforce how to get the last any number of days ago data records via soql
•18 min read

Here's the best ways to fetch “last N days” records in Salesforce using SOQL, along with clear examples.
✅ SOQL: Get Last N Days Records
Salesforce SOQL provides built-in date literals to query recent or past data easily.
1. Using LAST_N_DAYS:n
Fetch records from the last n days (including today).
✔ Example: Last 7 days
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate = LAST_N_DAYS:7
JavaScript✔ Example: Last 30 days
SELECT Id, Name, CreatedDate<br>FROM Opportunity<br>WHERE CloseDate = LAST_N_DAYS:30<br>JavaScript2. Using N_DAYS_AGO:n
Fetch records created exactly n days ago.
✔ Example: Records created exactly 10 days ago
SELECT Id, Name, CreatedDate
FROM Lead
WHERE CreatedDate = N_DAYS_AGO:10
JavaScript3. Using Greater Than / Less Than With N_DAYS_AGO
You can also create a range:
✔ Example: Records from last 15 days but not today
SELECT Id, Name, CreatedDate
FROM Case
WHERE CreatedDate >= N_DAYS_AGO:15
AND CreatedDate < TODAY
JavaScript4. Using Custom Apex Logic for Dynamic n
If n is dynamic (entered by user), use Apex:
✔ Apex Example
Integer n = 20; // you can pass dynamic N
Date targetDate = Date.today().addDays(-n);
List<Contact> cons = [
SELECT Id, Name, CreatedDate
FROM Contact
WHERE CreatedDate >= :targetDate
];
JavaScript5. Apex + SOQL: Last N Days Records
public with sharing class FetchLastNDaysRecords {
public static List<Opportunity> getLastNDaysOpps(Integer n) {
return [
SELECT Id, Name, Amount, CreatedDate
FROM Opportunity
WHERE CreatedDate = LAST_N_DAYS : n
];
}
}
JavaScript⭐ Full Working Apex Example (With Return Response)
public class GetLastDaysData {
@AuraEnabled(cacheable=true)
public static List<Account> getLastNDaysAccounts(Integer nDays) {
// Query records for last N days
List<Account> accList = [
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate = LAST_N_DAYS : nDays
];
return accList; // returns list to LWC/Aura
}
}
JavaScriptSummary
| Requirement | SOQL |
|---|---|
| Last 7 days | LAST_N_DAYS:7 |
| Last 30 days | LAST_N_DAYS:30 |
| Exactly 5 days ago | N_DAYS_AGO:5 |
| Dynamic days from Apex | Date.today().addDays(-n) |
Related Posts

How to Automatically create a follow-up Task when a Lead is converted

How You need to update a related child record whenever a parent record’s status changes, but only if the status is “Closed Won.” How would you design this in Apex?
