• 1Installation
  • 2Simple queries
  • 3Fields Selection
  • 4Fields Selection Continued
  • 5Conditions
  • 6Conditions Part 2
  • 7Conditions Part 3
  • 8Subqueries
  • 9Aggregate Functions Part 1
  • 10Aggregate Functions Part 2
  • 11Aggregate Functions Part 3

Query.apex

  • Docs
  • Tutorials
Getting started with Query.apex

16 min 30 sec

Fields Selection Continued

It's also possible to include fields from a parent. The easiest way would be passing the parent name to the 'selectAllFields' method:

List<Account> accounts =
    new Query('Account').
    selectAllFields('Owner').
    run();
xxxxxxxxxx
 
1
List<Account> accounts =
2
    new Query('Account').
3
    selectAllFields('Owner').
4
    run();

This would select the Id field in Account object, as weel as all the user accessible fields in the Owner reference, which is a User object.

The statement is equivalent to:

List<Account> accounts =
    [ SELECT Id, Owner.Id, Owner.Name, Owner.CreatedById ... FROM Account ];
xxxxxxxxxx
 
1
List<Account> accounts =
2
    [ SELECT Id, Owner.Id, Owner.Name, Owner.CreatedById ... FROM Account ];

Another way would be simply passing the parent field along with the relationship to the 'selectFields' method:

List<Account> accounts =
    new Query('Account').
    selectFields('Owner.Name, Owner.CreatedById').
    run();
xxxxxxxxxx
 
1
List<Account> accounts =
2
    new Query('Account').
3
    selectFields('Owner.Name, Owner.CreatedById').
4
    run();

equivalent to:

List<Account> accounts =
    [ SELECT Id, Owner.Name, Owner.CreatedById FROM Account ];
xxxxxxxxxx
 
1
List<Account> accounts =
2
    [ SELECT Id, Owner.Name, Owner.CreatedById FROM Account ];

Meanwhile, multiple layer parent relationship is supported:

List<Account> accounts =
    new Query('Contact').
    selectFields('Account.Owner.Name').
    run();
xxxxxxxxxx
 
1
List<Account> accounts =
2
    new Query('Contact').
3
    selectFields('Account.Owner.Name').
4
    run();
Done
Copy