Object alias in SOQL

The object alias used in SOQL can reduce the number of characters in query string and improve the readability. Suppose there are these objects with parent-child relationship:

  • Parent: ObjectA
  • Child: ObjectB
  • Grand Child: ObjectC

And all of these objects have three fields: Field1, Field2 and Field3. A normal SOQL statement that join these objects from the lowest level of the object graph looks like:

List<ObjectC__c> cList = [
        select
                Field1__c,
                Field2__c,
                Field3__c,
                ObjectB__r.Field1__c,
                ObjectB__r.Field2__c,
                ObjectB__r.Field3__c,
                ObjectB__r.ObjectA__r.Field1__c,
                ObjectB__r.ObjectA__r.Field2__c,
                ObjectB__r.ObjectA__r.Field3__c
        from ObjectC__c
];

The version with object alias looks like this:

List<ObjectC__c> cList = [
        select
                objC.Field1__c,
                objC.Field2__c,
                objC.Field3__c,
                objB.Field1__c,
                objB.Field2__c,
                objB.Field3__c,
                objA.Field1__c,
                objA.Field2__c,
                objA.Field3__c
        from ObjectC__c objC, objC.ObjectB__r objB, objB.ObjectA__r objA
];

Notice that all involved objects are specified in the “from” clause. This is really a sort of DRYness which makes the SOQL less verbose. It is particularly useful in the case that the number of characters is limited such as SOQL queries being used in HTTP GET URLs as part of the REST web service calls.

Published by Chun Wu

When nothing is certain, anything is possible.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: