SOQL Date Literals
SOQL has a brilliant and time-saving feature for comparing date values, which is called Date Literals. They are fixed string constants used to specify a date range without the need to quote specific dates. They can work with both with Date and Datetime Comparisons.
Say, for instance, you want to find all the patients whose birthday is in the current month. Let’s assume the current Month is August 2019.
So SOQL query can be:
This query works, but there is a lot of effort.
- You have to determine the current month.
- You have to calculate the start date and end date of the month.
- You have to check if the month contains 30 or 31 days. And yes, 28, 29 sometimes.
The requirement can be handled very easily by using Date Literals.
The same SOQL query can be rewritten as:
A lot more intuitive query, easier to read, and easier to maintain.
Following a list of the most used Date literals, you can find an exhaustive list here.
Date Literal | Description | Example |
---|---|---|
YESTERDAY | Begins at 00:00 in the previous day, and continues for 24 hours | |
TODAY | Begins at 00:00 in the current day, and continues for 24 hours | |
TOMORROW | Begins at 00:00 the next day, and continues for 24 hours | |
LAST_WEEK | Begins at 00:00 on Monday for the previous week, and continues for 7 full days | |
THIS_WEEK | Begins at 00:00 on Monday of this week, and continues for 7 full days | |
NEXT_WEEK | Begins at 00:00 on Monday for next week, and continues for 7 full days | |
LAST_MONTH | Begins at 00:00 on 1st day of the previous month and continues till the last day of that month | |
THIS_MONTH | Begins at 00:00 on 1st day of this month and continues till the last day of this month. | |
NEXT_MONTH | Begins at 00:00 on 1st day of the next month and continues till the last day of next month. | |
THIS_YEAR | Begins at 00:00 on 1st day of this Year, and continues till the last day of the year. | |
LAST_N_DAYS:n | Begins at 00:00 in the current day and continues for n past days. n is a positive Integer variable. |
Appointments for the past 3 days |
NEXT_N_DAYS:n | Begins at 00:00 the next day, and continues for n future days.n is a positive Integer variable. |
Appointments for the next 3 days |