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.
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
AND AnnualRevenue > 1000000
ORDER BY Name
LIMIT 50Upper-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.
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.
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:
SELECTFROMUSING SCOPEWHEREWITHGROUP BYHAVINGORDER BYLIMITOFFSETFOR VIEW,FOR REFERENCEorFOR 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.