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 \N | New line |
\r or \R | Carriage return |
\t or \T | Tab |
\b or \B | Bell |
\f or \F | Form field. |
\” | one double quote character |
\’ | Backslash |
\_ | Matches a single underscore character ( _ ). |
\% | Matches a single percent sign character ( % ). |
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.
Format | Format Syntax | Example |
---|---|---|
Date only | YYYY-MM-DD | 1999-01-01 |
Date, time, and time zone offset |
|
|
Conclusion
In this Apex Tutorial, we learned the syntax and examples for Field Expression of the WHERE clause in a SOQL query.