SOQL Style Guidelnes - Large SELECT Clause
The convention I adopt when selecting many fields is to:
- Put the
SELECT
clause on its own line - Indent each line in the actual fields by 1 tab/4 spaces
- Generally put as many fields as possible on one line without overrunning 80/100/120 according to line length preference
- Put each sub-query on its own line
- I also find it's best to put each clause on its own line, including
WHERE
and all its sub-clauses,GROUP BY
,LIMIT
, etc.
Example
List<MyObject__c> records = [
SELECT
Field1__c, Field2__c, Field3__c,
Field4__c, Field5__c, Field6__c,
(SELECT Field__c FROM Children1__c),
(SELECT Field__c FROM Children2__c)
FROM MyObject__c
WHERE Condition1
AND Condition2
GROUP BY Field1__c
ORDER BY Field1__c
LIMIT 1000
];
That said, your format shouldn't really matter, and I've found getting hung up on this stuff does not make me a better programmer or colleague during peer review. The above is developed 100% based on my personal preference, and there are many other valid approaches.
Generally I try to take up as few lines as possible without making any individual line excessively long. So I relax the one-lining to some extent based on that. Some other formats that litter my own codebase:
List<MyObject__c> records = [SELECT SingleField__c FROM MyObject__c];
for (MyObject__c record : [
SELECT Field1__c, Field2__c, Field3__c, Field4__c
FROM MyObject WHERE Field5__c = :value
ORDER BY Field1__c DESC
]) // do stuff
While this remains open, I'll extend it to include how static SOQL fits with other code elements and offer this as an example:
for (Diagnosis__c d : [
select Id, MedicalCodeType__c, Journal__c
from Diagnosis__c
where Journal__c in :journals
and Id not in :exclusions
]) {
// ...
}
where the main point is that the major structural elements of the SOQL are left clear of other language tokens and separated by line feeds. The double indent implies a continuation of an element to differentiate that from a new block.
Personally not fond of capitalizing in SOQL as that requires better keyboard skills than I have to do consistently and quickly.
(This style of for
loop avoids the need for a variable to hold the list - often not needed - and for big queries is kinder on heap usage.)