Salesforce SOQL Date Literals

Todays PD1 study had me reviewing SOQL. Most of the review was around things I already know and employ regularly, except for one thing – Date Literals.

A fieldExpression can use a date literal to compare a range of values to the value in a date or dateTime field. Each literal is a range of time beginning with midnight (00:00:00). To find a value within the range, use =. To find values on either side of the range, use > or <. The following table shows the available list of date literals, the ranges they represent, and examples.

I had no idea that you could query based on date literals although it makes sense. I’ve used similar date/time functionality in MySQL so it wasn’t a surprise that they existed, I’d just never run into a situation where I needed to use them in Salesforce.

If you haven’t used them (and you have a use case where they’d make sense), you should. They make life a whole lot easier. For example, this:

SELECT Id, Name FROM Contact WHERE CreatedDate >= 2019-01-02T00:00:00Z AND CreatedDate < 2019-01-03T00:00:00Z

Could be simplified into this:

SELECT Id, Name FROM Contact WHERE CreatedDate = TODAY

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.