Apex SOQL Field Expressions

A SOQL field expression is the condition you write inside the WHERE clause to filter Salesforce records. It contains a field name, a comparison operator, and a value. In Apex, the value can be a literal value, a date literal, a bind variable, or a collection used with operators such as IN.

FieldName ComparisonOperator Value

This tutorial explains SOQL field expression syntax, escape sequences, date literals, date and DateTime formats, and common Apex examples. For the full reference, use Salesforce’s official SOQL documentation for SELECT syntax and condition expressions.

Basic SOQL WHERE Field Expression Syntax in Apex

A field expression is normally written after WHERE. The field must belong to the queried object, or to a valid relationship path from that object.

</>
Copy
SELECT Id, Name
FROM Account
WHERE Industry = 'Education'

In the above query, Industry = 'Education' is the field expression. Industry is the field name, = is the comparison operator, and 'Education' is the value.

SOQL Comparison Operators Used in Field Expressions

SOQL supports comparison operators that are used to compare field values with literals, variables, lists, or date ranges.

OperatorMeaning in SOQLExample condition
=EqualsName = 'TutorialKart'
!=Not equal toIndustry != 'Banking'
<Less thanAmount < 10000
<=Less than or equal toCloseDate <= TODAY
>Greater thanAnnualRevenue > 500000
>=Greater than or equal toCreatedDate >= LAST_N_DAYS:30
LIKEPattern match for textName LIKE 'Tut%'
INMatches any value in a listId IN :accountIds
NOT INExcludes values in a listStatus__c NOT IN ('Closed','Cancelled')
INCLUDESMatches values in a multi-select picklistSkills__c INCLUDES ('Apex')
EXCLUDESExcludes values in a multi-select picklistSkills__c EXCLUDES ('Apex')

Use AND, OR, and parentheses when more than one field expression is required.

</>
Copy
SELECT Id, Name
FROM Contact
WHERE Email != null
AND (LeadSource = 'Web' OR LeadSource = 'Phone Inquiry')

Writing SOQL Queries Inside Apex with Bind Variables

When a SOQL query is written inside Apex, bind variables are preferred over string concatenation. A bind variable is written with a colon before the Apex variable name.

</>
Copy
String accountName = 'TutorialKart';
List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Name = :accountName
];

Bind variables make Apex SOQL easier to read and help avoid unsafe dynamic query construction. They can be used with single values, sets, lists, and other supported Apex variables.

</>
Copy
Set<Id> accountIds = new Set<Id>();
accountIds.add('001000000000001AAA');
accountIds.add('001000000000002AAA');

List<Contact> contacts = [
    SELECT Id, FirstName, LastName, AccountId
    FROM Contact
    WHERE AccountId IN :accountIds
];

SOQL Escape Sequences for Quotes, Tabs, New Lines, LIKE Percent and Underscore

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

\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 ( % ).

In practice, the most common escape cases are single quotes in text values and the % or _ wildcard characters in LIKE expressions. In a LIKE pattern, % matches zero or more characters and _ matches exactly one character. Escape them when you want to search for the literal character.

Examples – Escaped Characters

</>
Copy
SELECT Id FROM Account WHERE Name LIKE 'Tut%';

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

</>
Copy
SELECT Id FROM Account WHERE Name LIKE 'Tut\%';

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

</>
Copy
SELECT Id FROM Account WHERE Name LIKE 'Tut\%%';

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

Escaping Single Quotes in Dynamic Apex SOQL

If you build a dynamic SOQL string in Apex, escape user-entered text before placing it inside a quoted string. Prefer bind variables where possible. If dynamic SOQL is required, use String.escapeSingleQuotes() for text values.

</>
Copy
String searchText = 'Bob\'s Bakery';
String safeSearchText = String.escapeSingleQuotes(searchText);

String queryText = 'SELECT Id, Name FROM Account WHERE Name = \'' + safeSearchText + '\'';
List<Account> accounts = Database.query(queryText);

For static SOQL in Apex, use a bind variable instead of joining strings.

</>
Copy
String searchText = 'Bob\'s Bakery';
List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Name = :searchText
];

Date Literals and Date Formats in SOQL WHERE Conditions

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 ...

The examples above show the idea of date filtering. In real SOQL, make sure the field API name is valid, such as Joining_Date__c, and the date literal name is typed correctly.

SOQL date literalWhat it filtersCorrect example
YESTERDAYRecords dated yesterdayJoining_Date__c = YESTERDAY
TODAYRecords dated todayJoining_Date__c = TODAY
TOMORROWRecords dated tomorrowJoining_Date__c = TOMORROW
LAST_WEEKRecords in last weekJoining_Date__c = LAST_WEEK
THIS_WEEKRecords in this weekJoining_Date__c = THIS_WEEK
NEXT_WEEKRecords in next weekJoining_Date__c = NEXT_WEEK
LAST_MONTHRecords in last monthJoining_Date__c = LAST_MONTH
THIS_MONTHRecords in this monthJoining_Date__c = THIS_MONTH
NEXT_MONTHRecords in next monthJoining_Date__c = NEXT_MONTH
LAST_N_DAYS:nRecords from the previous n days, including todayCreatedDate = LAST_N_DAYS:30
NEXT_N_DAYS:nRecords in the next n daysActivityDate = NEXT_N_DAYS:7

For Apex practice, Salesforce Trailhead has a useful module on writing SOQL queries in Apex.

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

For a Date field, a date-only value such as 2026-06-22 is enough. For a DateTime field such as CreatedDate, use a full DateTime value with a time zone, or use a SOQL date literal.

</>
Copy
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate >= 2026-06-01T00:00:00Z
AND CreatedDate < 2026-07-01T00:00:00Z

The Z suffix represents UTC time. If you use a time zone offset, write it in the supported format, for example 2026-06-01T00:00:00+05:30.

Getting Many Fields from an Object in SOQL with FIELDS()

To query many fields without listing every field name manually, SOQL supports the FIELDS() function in supported API contexts. It is commonly used as FIELDS(STANDARD), FIELDS(CUSTOM), or FIELDS(ALL). Use it carefully because querying too many fields can increase response size and affect performance.

</>
Copy
SELECT FIELDS(STANDARD)
FROM Account
LIMIT 10

For production Apex, it is usually better to select only the fields the code actually uses. This keeps queries clear and avoids retrieving unnecessary data.

Common SOQL Field Expression Mistakes in Apex

  • Using the field label instead of the API name: SOQL needs Joining_Date__c, not the label shown on the page layout.
  • Forgetting quotes around string values: Text and picklist values must be quoted, for example Status__c = 'Active'.
  • Quoting date literals: Write CreatedDate = TODAY, not CreatedDate = 'TODAY'.
  • Using = null incorrectly in logic: SOQL supports null comparisons, but make sure the field type and business meaning are correct.
  • Building unsafe dynamic SOQL: Prefer bind variables. When dynamic SOQL is necessary, escape text and validate field names or object names before adding them to the query string.

Apex SOQL Field Expression Quick Reference

NeedUse this SOQL pattern
Exact text matchName = 'TutorialKart'
Starts with textName LIKE 'Tut%'
Literal percent signName LIKE 'Tut\%'
Records from todayCreatedDate = TODAY
Records from last 30 daysCreatedDate = LAST_N_DAYS:30
Filter by Apex variableName = :accountName
Filter by multiple IDsId IN :recordIds
Check blank lookup or text fieldParentId = null

FAQs on Apex SOQL Field Expressions, Date Literals and Escape Sequences

How to write a SOQL query in Apex?

Write a static SOQL query inside square brackets and assign the result to a list or a single sObject. Example: List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name = :accountName];. Use bind variables with a colon when the value comes from Apex.

What is the basic syntax of a SOQL field expression?

The basic syntax is FieldName ComparisonOperator Value. For example, Industry = 'Education', CreatedDate >= LAST_N_DAYS:30, and Id IN :accountIds are valid field expressions when the fields and variables exist.

How do I escape a percent sign in a SOQL LIKE query?

Use a backslash before the percent sign when you want to match the literal % character. Example: Name LIKE 'Tut\%' searches for Tut% exactly, while Name LIKE 'Tut%' searches for names that start with Tut.

Should TODAY be written inside quotes in SOQL?

No. SOQL date literals are not written inside quotes. Use CreatedDate = TODAY or CloseDate = NEXT_MONTH. A literal date value such as 2026-06-22 is also written without single quotes in SOQL.

How to get all fields of an object in SOQL?

Use FIELDS(STANDARD), FIELDS(CUSTOM), or FIELDS(ALL) where supported. Example: SELECT FIELDS(STANDARD) FROM Account LIMIT 10. In Apex business logic, selecting only the required fields is usually safer and clearer.

Editorial QA Checklist for This Apex SOQL Tutorial

  • Verify that every SOQL field expression uses a valid API field name, not a field label.
  • Check that all new code blocks use PrismJS language classes such as language-sql syntax or language-java syntax.
  • Confirm that date literals such as TODAY, LAST_WEEK, and LAST_N_DAYS:30 are not placed inside single quotes.
  • Review examples using LIKE so that wildcard matching and escaped literal % or _ characters are explained separately.
  • Prefer Apex bind variables over dynamic SOQL concatenation unless the example is specifically about dynamic SOQL.

Conclusion

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