Alias Notations in Salesforce SOQL

In Salesforce, while working with SOQL queries, we need to write the queries correctly to retrieve the data and make it understandable to the user. In Salesforce, we have the feature of “aliasing” names; for example, the user name John Smith will appear as jsmith in the alias name.

We can also use the alias notations in Salesforce SOQL to write queries. In this tutorial, I will explain the alias notations in the context of SOQL and how to use them in SOQL queries.

What is the Alias Notation in Salesforce SOQL?

In Salesforce SOQL, “Alias Notation” refers to a way to give a shorter, more descriptive name to an object or field within a query, allowing us to reference it more quickly in the rest of the SELECT statement, mainly when dealing with complex queries involving multiple objects or fields with similar names; essentially, it’s a nickname for a specific field or object we’re querying.

This is useful when working with relationship queries (parent-to-child or child-to-parent) where object names can get lengthy.

Object Aliases in the SOQL SELECT Clause

In SOQL queries, aliasing the fields will let us give a shorter or more meaningful name to fields in the query result.

SOQL query with alias object name:

Let’s take an example where we display the account records using the account object’s alias name, ‘Acct.‘

SELECT Acct.Id, Acct.name FROM Account Acct

Output:

How to alias objects in Salesforce SOQL

In the above SOQL statement, we have fetched the account ID and account name records from the standard object called Account. We have mentioned the word “Acct, ” the alias name for “Account.”  We can fetch data directly without using the object name.

Use Alias Name in SOQL Relationship Queries

In Salesforce, for using aliases in the SOQL queries, we don’t have the AS keyword like SQL. Instead, we can assign aliases by specifying them in aggregate functions or when selecting custom fields.

For querying related objects, we can alias the fields by using their relationship names, as shown in the syntax below.

SELECT Name, (SELECT LastName, Email FROM Contacts) contactDetails
 FROM Account

In the output, we can see that the contact details related to the parent account are aliased as contactDetails.

Use Alias Name in SOQL Relationship Queries

This way, we can refer to and use alias names for the objects having relationships in Salesforce SOQL by following the above syntax.

Aliasing Columns in SOQL query with Aggregate Functions