Does LAST N DAYS in Soql include TODAY?

1.3K    Asked by DavidEdmunds in Salesforce , Asked on Feb 27, 2023

 I would like to ask about the definition of LAST_N_DAYS:n


For the number n provided, starts 00:00:00 of the current day and continues for the past n days.


Is
CreatedDate = LAST_N_DAYS:1
equal to
(CreatedDate >= 2017-08-30T00:00:00Z AND CreatedDate <= 2017-08-30T23:59:59Z)
OR CreatedDate  = TODAY
and
CreatedDate >= YESTERDAY
To be more specific, aren't LAST_N_DAYS in fact LAST_N_DAYS + 1 (Today)?

In contradiction to what the current documentation claims, you can observe that the LAST_N_DAYS in soql date literally includes today's data.


To be sure, I ran this query:
SELECT CreatedDate FROM MyObject__c
WHERE CreatedDate = LAST_N_DAYS:1
ORDER BY CreatedDate DESC LIMIT 1
And I got back:
2017-08-31T18:16:17.000+0000

Your Answer

Answer (1)

In Salesforce Object Query Language (SOQL), the LAST_N_DAYS:n date literal includes today in the range of days. This means that when you use LAST_N_DAYS:n, the query will include records from today and the previous n-1 days.

To illustrate this with an example, let's consider you want to fetch records from the last 7 days including today. The SOQL query would look like this:

SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate = LAST_N_DAYS:7

This query retrieves all Account records where the CreatedDate is within the last 7 days, including today.

Clarification

  • If today is May 29th: LAST_N_DAYS:7 will include records from May 23rd to May 29th, inclusive.
  • If today is May 29th and time is 3 PM: It includes records created from 12:00 AM on May 23rd to the current time on May 29th (3 PM).

Testing with Real Data

To ensure you understand how this works with your data:
Create Test Records: Insert records with known CreatedDate values.
Run Queries: Use LAST_N_DAYS:n in your queries and observe the results to confirm it includes today.

Here’s a more concrete example with comments:

This will return contacts created from May 23rd to May 29th, inclusive.

Additional Date Literals

  • To provide more context, here are other useful date literals in SOQL:
  • YESTERDAY: Includes only yesterday’s records.
  • TODAY: Includes only today’s records.
  • TOMORROW: Includes only tomorrow’s records.
  • LAST_WEEK: Includes all records from last week.
  • THIS_WEEK: Includes all records from this week.
  • NEXT_WEEK: Includes all records from next week.
  • LAST_MONTH: Includes all records from last month.
  • THIS_MONTH: Includes all records from this month.
  • NEXT_MONTH: Includes all records from next month.
  • LAST_N_DAYS:n: Includes the last n days including today.
  • NEXT_N_DAYS:n: Includes the next n days including today.

Conclusion

Yes, LAST_N_DAYS:n in SOQL includes today as part of the n days. This is useful for queries where you want to consider data from the current day and a set number of days preceding it.



4 Months

Interviews

Parent Categories