Relationship Queries

Client applications need to be able to query for more than a single type of object at a time. SOQL provides syntax to support these types of queries, called relationship queries, against both standard objects and custom objects.

Relationship queries traverse parent-to-child and child-to-parent relationships between objects to filter and return results. They are similar to SQL joins. You cannot perform arbitrary SQL joins, however. The relationship queries in SOQL must traverse a valid relationship path as defined in the rest of this section.

You can use relationship queries to search for objects of one type based on criteria that applies to objects of another type, for example, “return all accounts created by Bob Jones and the contacts associated with those accounts.” There must be a parent-to-child or child-to-parent relationship connecting the objects. You can’t write arbitrary queries such as “return all accounts and users created by Bob Jones.”

Use the following topics to understand and use relationship queries in SOQL:

Understanding Relationship Names

Parent-to-child and child-to-parent relationships exist between many types of objects, for example, Account is a parent of Contact.

To be able to traverse these relationships for standard objects, a relationship name is given to each relationship. The form of the name is different depending on the direction of the relationship:

Warning
You must use the correct naming convention and SELECT syntax for the direction of the relationship. For information about how to discover relationship names via your organization's WSDL or describeSObjects(), see Identifying Parent and Child Relationships. There are limitations on relationship queries depending on the direction of the relationship. See Understanding Relationship Query Limitations for more information.

Relationship names are somewhat different for custom objects, though the SELECT syntax is the same. See Understanding Relationship Names and Custom Objects and Custom Fields for more information.

Using Relationship Queries

You can query the following relationships using SOQL:

Understanding Relationship Names and Custom Objects and Custom Fields

Custom objects can participate in relationship queries. Salesforce.com ensures that your custom object names, custom field names, and the relationship names associated with them remain unique, even if a standard object with the same name is available now or in the future. This is important in relationship queries, where the query traverses relationships using the object, field, and relationship names.

This section explains how relationship names for custom objects and custom fields are created and used.

When you create a new custom relationship in the Salesforce.com user interface, you are asked to specify the plural version of the object name, which you use for relationship queries:

Notice that the Child Relationship Name (parent to child) is the plural form of the child object name, in this case Daughters.

Once the relationship is created, notice that it has an API Name, which is the name of the custom field you created, appended by __c (underscore-underscore-c):

When you refer to this field via the API, you must use this special form of the name. This prevents ambiguity in the case where salesforce.com may create a standard object with the same name as your custom field. The same process applies to custom objects—when they are created, they have an API Name, the object named appended by __c, which must be used.

When you use a relationship name in a query, you must use the relationship names without the __c. Instead, append an __r (underscore underscore r).

For example:

Understanding Query Results

Query results are returned as nested objects. The primary or “driving” object of the main SELECT query contains query results of subqueries.

For example, you can construct a query using either parent-to-child or child-to-parent syntax:

Subquery results are like regular query results in that you may need to use queryMore() to retrieve all the records if there are many children. For example, if you issue a query on accounts that includes a subquery, your client application must handle results from the subquery as well:
  1. Perform the query on Account.
  2. Iterate over the account QueryResult with queryMore().
  3. For each account object, retrieve the contacts QueryResult.
  4. Iterate over the child contacts, using queryMore() on each contact's QueryResult.

The following sample illustrates how to process subquery results:


    private void querySample() {
        QueryResult qr = null;
        try {
            qr = binding.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 = binding.queryMore(qr.getQueryLocator());
                    }
                }
            } else {
                System.out.println("No records found.");
            }
            System.out.println("\nQuery succesfully executed.");
        }
        catch (RemoteException ex) {
            System.out.println("\nFailed to execute query successfully, error message " +
                 "was: \n" + ex.getMessage());
        }
    }
    
    private void printContacts(QueryResult qr) throws RemoteException {
        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 = binding.queryMore(qr.getQueryLocator());
                }
            }
        } else {
            System.out.println("No child contacts found.");
        }
    }

Lookup Relationships and Outer Joins

Beginning with version 13.0 of the API, relationship queries return records even if the relevant foreign key field has a null value, as you would expect with an outer join. The change in behavior applies to the following types of relationship queries:

Identifying Parent and Child Relationships

You can identify parent-child relationships by viewing the ERD diagrams in Data Model. However, not all parent-child relationships are exposed in SOQL, so to be sure you can query on a parent-child relationship by issuing the appropriate describe call. The results contain parent-child relationship information.

You can also examine the enterprise WSDL for your organization:

Understanding Polymorphic Keys and Relationships

A polymorphic key is an ID that can refer to more than one type of object as a parent. For example, either a contact or a lead can be the parent of a task. In other words, the WhoId field of a task can contain the ID of either a contact or a lead. If an object can have more than one type of object as a parent, the polymorphic key points to a Name object instead of a single object type.

Executing a describeSObjects() call returns the Name object, whose field Type contains a list of the possible object types that can parent the queried object. The namePointing field in the DescribeSObjectResult indicates that the relationship points to the Name object, needed because the relationship is polymorphic. For example, the value in WhoId on Task can be a contact or lead.

In order to traverse relationships where the object type of the parent is not known, you can use these fields to construct a query:

You can also use describeSObjects() to obtain information about the parents and children of objects. For more information, see describeSObjects() and especially namePointing, which, if set to true, indicates the field points to a name.

Understanding Relationship Query Limitations

When designing relationship queries, consider these limitations:

Using Relationship Queries with History Objects

Custom objects and some standard objects have an associated history object that tracks changes to an object record. You can use relationship queries to traverse a history object to its parent object. For example, the following query returns every history row for Foo__c and displays the name and custom fields of Foo:

     SELECT OldValue, NewValue, Parent.Id, Parent.name, Parent.customfield__c 
        FROM foo__history

This example query returns every Foo object row together with the corresponding history rows in nested subqueries:

     SELECT Name, customfield__c, (SELECT OldValue, NewValue FROM foo__history) 
       FROM foo__c

Using Relationship Queries with the Partner WSDL

The partner WSDL does not contain the detailed type information available in the enterprise WSDL to get the information you need for a relationship query. You must first execute a describeSObjects() call, and from the results, gather the information you need to create your relationship query:
  • The relationshipName value for one-to-many relationships, for example, in an Account object, the relationship name for the asset child is Assets.
  • The reference fields available for the relevant object, for example, whoId, whatId, or ownerId on a Lead, Case, or custom object.

For an example of using the partner WSDL with relationship queries, see the examples on developer.force.com (requires login).

© Copyright 2000-2010 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.