Skip to content

A SOQL style guide: writing queries your team can review

Conventions for readable SOQL: one clause per line, field lists, subqueries, bind variables and the clause order Salesforce expects.

5 minute readUpdated By Kappa Vinay

SOQL tends to be written once and read many times: in code review, in a debug log at the end of a long day, in a pull request diff. A few layout conventions make queries far easier to scan, and make changes show up as small, obvious diffs.

One clause per line

Start SELECT, FROM, WHERE, GROUP BY, ORDER BY and LIMIT on their own lines. When someone adds a filter, the diff shows one new line rather than a changed 300-character string.

SOQL
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
  AND AnnualRevenue > 1000000
ORDER BY Name
LIMIT 50

Upper-case keywords, API-case names

SOQL is not case-sensitive, so this is purely for the reader. Upper-case keywords separate the structure of the query from field and object names, which should keep the exact casing of their API names.

Long field lists: one field per line

Once a query selects more than three or four fields, put each on its own line. Adding or removing a field then touches exactly one line, and merge conflicts become rare.

Indent subqueries

Child relationship subqueries in the field list and semi-joins in the WHERE clause are queries in their own right. Indent them so their clauses line up with each other, not with the parent’s.

SOQL
SELECT
  Id,
  Name,
  (
    SELECT Id, LastName
    FROM Contacts
    WHERE Email != null
  )
FROM Account
WHERE Id IN (
    SELECT AccountId
    FROM Opportunity
    WHERE IsWon = true
  )

Put AND and OR at the start of the line

Leading operators make the logic visible down the left edge. Keep parentheses around any group that mixes AND with OR; SOQL requires them, and they stop readers from guessing.

Use bind variables instead of building strings

In Apex, reference variables with a colon rather than concatenating values into the query text. It is shorter, it is type-safe, and it removes the risk of SOQL injection.

Apex
List<Contact> contacts = [
    SELECT Id, Email
    FROM Contact
    WHERE AccountId IN :accountIds
      AND LastName = :lastName
];

The order Salesforce expects

Clauses must appear in a fixed order. The common ones are:

  1. SELECT
  2. FROM
  3. USING SCOPE
  4. WHERE
  5. WITH
  6. GROUP BY
  7. HAVING
  8. ORDER BY
  9. LIMIT
  10. OFFSET
  11. FOR VIEW, FOR REFERENCE or FOR UPDATE

Formatting changes how a query looks, not how it runs. To check field names, relationships and selectivity you still need to run the query against an org.