Intermediate 15 min read

Date Literals and Relative Date Filtering

By the end of this lesson, you'll be able to:

  • Filter SOQL queries using relative date literals like THIS_MONTH and LAST_N_DAYS
  • Explain why relative date literals are preferred over hardcoded dates in reusable queries

Prerequisites: Aggregate Functions and GROUP BY

Common date literals

SOQL ships with a set of built-in date literals — TODAY, YESTERDAY, THIS_WEEK, THIS_MONTH, THIS_YEAR, LAST_N_DAYS:n, NEXT_N_DAYS:n, and more. They're used directly in a WHERE clause against a Date or Datetime field, with no quotes.

Why relative, not hardcoded

A report or dashboard that runs daily or weekly needs its date window to shift automatically. Hardcoding CreatedDate > 2026-01-01 would need manual updates forever; CreatedDate = LAST_N_DAYS:30 always means "the last 30 days," relative to whenever the query actually runs.

This month's open Opportunities

SELECT Id, Name, CloseDate
FROM Opportunity
WHERE CloseDate = THIS_MONTH
AND IsClosed = false

THIS_MONTH automatically covers the 1st through the last day of whatever month the query happens to run in — no maintenance needed.

Exercise

Write a query returning Leads created in the last 7 days.

Show hint

CreatedDate = LAST_N_DAYS:7

SOQL

Date Literals and Relative Date Filtering — Quick Check

1. Which date literal covers the last 30 days relative to now?

2. Date literals need to be wrapped in quotes, like string values.

3. Why prefer THIS_MONTH over a hardcoded date range?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Date literals like TODAY, THIS_MONTH, and LAST_N_DAYS:n let a query's date range stay relative to whenever it runs, instead of hardcoding a date that goes stale.