Sunday, March 2, 2025

Date Literals in Salesforce SOQL

 Date literals in Salesforce Object Query Language (SOQL) allow you to filter records based on dynamic date ranges without needing exact date values. These literals are useful for queries that need to fetch records for predefined periods like today, last week, or the last 30 days.

 

Commonly Used SOQL Date Literals

Date Literal

Description

YESTERDAY

Records where the date is yesterday.

TODAY

Records where the date is today.

TOMORROW

Records where the date is tomorrow.

LAST_WEEK

Records from last week (Sunday to Saturday).

THIS_WEEK

Records from this current week (Sunday to Saturday).

NEXT_WEEK

Records from next week (Sunday to Saturday).

LAST_MONTH

Records from last month (1st to last day).

THIS_MONTH

Records from this current month (1st to today’s date).

NEXT_MONTH

Records from next month (1st to last day).

LAST_N_DAYS:n

Records from the last ‘n’ days, including today.

NEXT_N_DAYS:n

Records from the next ‘n’ days, including today.

LAST_N_WEEKS:n

Records from the last ‘n’ weeks.

NEXT_N_WEEKS:n

Records from the next ‘n’ weeks.

LAST_N_MONTHS:n

Records from the last ‘n’ months.

NEXT_N_MONTHS:n

Records from the next ‘n’ months.

THIS_YEAR

Records from this year (Jan 1 - Today).

LAST_YEAR

Records from last year (Jan 1 - Dec 31).

NEXT_YEAR

Records from next year (Jan 1 - Dec 31).

LAST_N_YEARS:n

Records from the last ‘n’ years.

NEXT_N_YEARS:n

Records from the next ‘n’ years.

 

Examples of SOQL Queries Using Date Literals

1. Get All Leads Modified Today


SELECT Id, Name, LastModifiedDate 
FROM Lead 
WHERE LastModifiedDate = TODAY

2. Get All Opportunities Created in the Last 7 Days


SELECT Id, Name, CreatedDate 
FROM Opportunity 
WHERE CreatedDate >= LAST_N_DAYS:7

3. Get All Cases Closed in the Last Month

SELECT Id, CaseNumber, Status 
FROM Case 
WHERE ClosedDate = LAST_MONTH

4. Get All Accounts Created in the Current Year


SELECT Id, Name, CreatedDate 
FROM Account 
WHERE CreatedDate >= THIS_YEAR

 

Why Use Date Literals?

  • Eliminates hardcoded date values (e.g., '2024-02-26').
  • Adapts dynamically to the current date.
  • Improves performance by simplifying queries.

 


No comments: