Understanding Query Results
Query results are returned as nested objects. The primary or “driving”
object of the main SELECT statement in a SOQL query contains
query results of subqueries.
For example, you can construct a query using either parent-to-child or child-to-parent syntax:
- Child-to-parent:
SELECT Id, FirstName, LastName, AccountId, Account.Name FROM Contact WHERE Account.Name LIKE 'Acme%'
This query returns one query result (assuming there were not too many returned records), with a row for every contact that met the WHERE clause criteria.
- Parent-to-child:
SELECT Id, Name, ( SELECT Id, FirstName, LastName FROM Contacts ) FROM Account WHERE Name like 'Acme%'
This query returns a set of accounts, and within each account, a query result set of Contact fields containing the contact information from the subquery.
The following sample illustrates how to process subquery results:
private void querySample() {
QueryResult qr = null;
try {
qr = connection.query("SELECT a.Id, a.Name, " +
"(SELECT c.Id, c.FirstName, " +
"c.LastName FROM a.Contacts c) FROM Account a");
boolean done = false;
if (qr.getSize() > 0) {
while (!done) {
for (int i = 0; i < qr.getRecords().length; i++) {
Account acct = (Account) qr.getRecords()[i];
String name = acct.getName();
System.out.println("Account " + (i + 1) + ": " + name);
printContacts(acct.getContacts());
}
if (qr.isDone()) {
done = true;
} else {
qr = connection.queryMore(qr.getQueryLocator());
}
}
} else {
System.out.println("No records found.");
}
System.out.println("\nQuery succesfully executed.");
} catch (ConnectionException ce) {
System.out.println("\nFailed to execute query successfully, error message " +
"was: \n" + ce.getMessage());
}
}
private void printContacts(QueryResult qr) throws ConnectionException {
boolean done = false;
if (qr.getSize() > 0) {
while (!done) {
for (int i = 0; i < qr.getRecords().length; i++) {
Contact contact = (Contact) qr.getRecords()[i];
String fName = contact.getFirstName();
String lName = contact.getLastName();
System.out.println("Child contact " + (i + 1) + ": " + lName
+ ", " + fName);
}
if (qr.isDone()) {
done = true;
} else {
qr = connection.queryMore(qr.getQueryLocator());
}
}
} else {
System.out.println("No child contacts found.");
}
}