Apex SOQL Field Expressions

The field expression syntax of the WHERE clause in a SOQL query consists of a field name, a comparison operator, and a value that’s used to compare with the value in the field name. In this Salesforce tutorial, we are going to learn about escape sequences in SOQl, Data formats and Date literals used in SOQL statement.

FieldName ComparisonOperator Value

SOQL defines several escape sequences that are valid in queries so that you can include special characters in your queries. You can escape new lines, carriage returns, tabs, quotes, and more. The escape character for SOQL is the backslash (\) character. Some of the escape sequences in SOQL are

SOQL Escape Sequences

\n or \NNew line
\r or \RCarriage return
\t or \TTab
\b or \BBell
\f or \FForm field.
\”one double quote character
\’Backslash
\_Matches a single underscore character ( _ ).
\%Matches a single percent sign character ( % ).
ADVERTISEMENT

Examples – Escaped Characters

SELECT Id FROM Account WHERE Name LIKE 'Tut%';

From above query, Select all accounts whose name begins with the three character sequences ‘Tut’.

SELECT Id FROM Account WHERE Name LIKE 'Tut\%';

It selects, all accounts whose name exactly matches the four character sequences ‘Tut%’.

SELECT Id FROM Account WHERE Name LIKE 'Tut\%%';

It selects, all accounts whose name begins with the four character sequence ‘Tut%’.

Date literals and Date Formats

Date literals in salesforce are used to compare a range of values to the value in the Date or dateTime field. When querying the record using the date field in SOQL statement, date literals are used and the each literal is a range of time beginning with midnight (00:00:00).

Some of the Date literals that can be used in SOQL statements are

 YESTERDAY
SELECT Id FROM Employee__c WHERE Joining_Date__c = YESTERDAY
TODAY
SELECT Id FROM Employee__c WHERE Joining_Date__c > TODAY
TOMORROW
SELECT Id FROM Employee__c WHERE Joining Date__c = TOMORROW
LAST_WEEK
SELECT Id FROM Employee__c WHERE Joining_Date__c > LAST_WEEK
THIS_WEEK
SELECT Id FROM Employee__c WHERE Joining_Date__c < THIS_WEEK
NEXT_MONTH
SELECT Id FROM Employee__c WHERE Joining_Date__c = NEXT_WEEK
LAST_-MONTH
SELECT Id FROM Employee__c WHERE Joining_Date__c > LAST_MONTH ...

Date Formats used  in SOQL Statements

In SOQL statement, fieldExpression used different  date formats for different Date and DateTime fields in Salesforce. This Date formats in SOQL are used to filter on dateTime fields.

Date formats in SOQL are as follows.

FormatFormat SyntaxExample
Date onlyYYYY-MM-DD1999-01-01
Date, time, and time zone offset
  • YYYY-MM-DDThh:mm:ss+hh:mm
  • YYYY-MM-DDThh:mm:ss-hh:mm
  • YYYY-MM-DDThh:mm:ssZ
  • 1999-01-01T23:01:01+01:00
  • 1999-01-01T23:01:01-08:00
  • 1999-01-01T23:01:01Z

Conclusion

In this Apex Tutorial, we learned the syntax and examples for Field Expression of the WHERE clause in a SOQL query.