Getting started with Query.apex
Fields Selection
By default Query.apex will select only the Id field in the SObject, however we can override this if we want to select other fields.
For example, this query will only select only the Name field from the Account object.
List accounts =
new Query('Account').selectFields('Name').run();
This is equivalent to:
List accounts =
[ SELECT Name FROM Account ];
We can also call 'selectFields' method multiple times, the result is additive:
List accounts =
new Query('Account').
selectFields('Name').
selectFields('Phone').
selectFields('Website').
selectFields('Description').
run();
That's equivalent to:
List accounts =
[ SELECT Name, Phone, Website, Description FROM Account ];
Alternatively, we can put all the fields in one 'selectFields' method, still preserving the additivity:
List accounts =
new Query('Account').
selectFields('Name, Phone, Website').
selectFields('Description').
run();
Compare with:
List fields = new List{'Name', 'Phone', 'Website'};
List accounts =
new Query('Account').
selectFields(fields).
selectFields('Description').
run();
or:
Set fields = new Set{'Name', 'Phone', 'Website'};
List accounts =
new Query('Account').
selectFields(fields).
selectFields('Description').
run();
To make user convenient, Query.apex provides the 'selectAllFields' method to select all user accessible fields:
List accounts =
new Query('Account').
selectAllFields().
run();