AI • Apex • Integration • Interview •

Advanced SOQL in Salesforce: Relationships, Aggregate Functions, Complex Filtering and Query Optimization

khumed Khatib 5 min read

KHUMEDSFDC | ADVANCED SALESFORCE DEVELOPMENT SERIES
Article 2 – Advanced SOQL

Advanced SOQL in Salesforce: Relationships, Aggregate Functions, Complex Filtering and Query Optimization

SOQL is one of the first things every Salesforce developer learns. Initially, we write simple queries to retrieve records from standard and custom objects. Something like this:

List<Account> accounts = [
    SELECT Id, Name, Industry
    FROM Account
];

This works perfectly when we only need basic information.

But real development requirements are rarely this simple.

Imagine a requirement where the business team asks you to retrieve Accounts along with their Contacts, calculate the total value of open Opportunities, find Accounts without Contacts, and allow users to search records using dynamic filters.

You can solve these requirements using multiple queries, but that is not always the best approach.

This is where advanced SOQL becomes important.

In this article, we will explore relationship queries, aggregate functions, GROUP BY, HAVING, semi-joins, anti-joins, dynamic SOQL, and query optimization using practical Salesforce examples.

1. Understanding Relationship Queries

In Salesforce, objects are connected through relationships. SOQL allows us to retrieve related records without writing separate queries for every object.

There are two important types of relationship queries:

  • Child-to-Parent (using dot notation).
  • Parent-to-Child (using a subquery).

1.1 Child-to-Parent Relationship Query

Let's consider the Contact and Account relationship. Every Contact can be associated with an Account. If we want to retrieve Contact details along with its Account information, we can use dot notation.

Example:

List<Contact> contacts = [
    SELECT Id,
           FirstName,
           LastName,
           Email,
           Account.Name,
           Account.Industry
    FROM Contact
    WHERE AccountId != null
];

for (Contact con : contacts) {
    System.debug('Contact: ' + con.Name);
    System.debug('Account: ' + con.Account.Name);
    System.debug('Industry: ' + con.Account.Industry);
}

Here, we are querying Contact records but accessing fields from the parent Account.

Notice Account.Name. We are not executing another SOQL query to get the Account name.

Real-time use case: Suppose you are developing an Employee Management application and every Employee record is associated with a Department. You can retrieve employee information along with the Department name in a single query using the relationship field.

1.2 Parent-to-Child Relationship Query

Now let's look at the opposite scenario.

Suppose we want to retrieve Accounts along with all their related Contacts.

List<Account> accounts = [
    SELECT Id,
           Name,
           Industry,
           (SELECT Id, FirstName, LastName, Email
            FROM Contacts)
    FROM Account
];

for (Account acc : accounts) {

    System.debug('Account Name: ' + acc.Name);

    for (Contact con : acc.Contacts) {
        System.debug('Contact Name: ' + con.Name);
    }
}

Here, Contacts is the child relationship name used in the Account query.

In parent-to-child queries, we use the relationship name, not necessarily the child object's API name.

2. Aggregate Functions in SOQL

Sometimes we don't need complete records. We only need numbers or summaries.

For example:

  • How many Accounts are present?
  • What is the total Opportunity amount?
  • What is the average Opportunity value?
  • What is the highest Opportunity amount?

Instead of retrieving every record and calculating everything in Apex, SOQL provides aggregate functions.

FunctionPurpose
COUNT()Counts records
COUNT(fieldName)Counts non-null field values
SUM()Calculates the total
AVG()Calculates the average
MIN()Returns the minimum value
MAX()Returns the maximum value

Example 1: Count Accounts

Integer totalAccounts = [
    SELECT COUNT()
    FROM Account
];

System.debug('Total Accounts: ' + totalAccounts);

Example 2: Calculate Total Opportunity Amount

AggregateResult result = [
    SELECT SUM(Amount) totalAmount
    FROM Opportunity
    WHERE IsClosed = false
];

Decimal totalAmount =
    (Decimal) result.get('totalAmount');

System.debug('Total Open Opportunity Value: ' + totalAmount);

Whenever we use aggregate functions, Salesforce returns aggregated data through AggregateResult.

We can access the calculated value using the alias:

result.get('totalAmount');

Example 3: Average Opportunity Amount

AggregateResult result = [
    SELECT AVG(Amount) averageAmount
    FROM Opportunity
    WHERE IsClosed = false
];

Decimal averageAmount =
    (Decimal) result.get('averageAmount');

System.debug('Average Amount: ' + averageAmount);

3. GROUP BY and HAVING

Aggregate functions become more useful when we combine them with GROUP BY.

Let's say your manager asks:

"Show me the total number of Opportunities and total Opportunity value for each Account."

We can solve this using GROUP BY.

Example: Group Opportunities by Account

List<AggregateResult> results = [
    SELECT AccountId,
           COUNT(Id) totalOpportunities,
           SUM(Amount) totalAmount
    FROM Opportunity
    WHERE AccountId != null
    AND IsClosed = false
    GROUP BY AccountId
];

for (AggregateResult ar : results) {

    Id accountId = (Id) ar.get('AccountId');

    Integer totalOpps =
        (Integer) ar.get('totalOpportunities');

    Decimal amount =
        (Decimal) ar.get('totalAmount');

    System.debug('Account Id: ' + accountId);
    System.debug('Total Opportunities: ' + totalOpps);
    System.debug('Total Amount: ' + amount);
}

This query groups Opportunities by Account. Instead of receiving every Opportunity record, we receive one summary row for each Account.

Understanding HAVING

Now let's make the requirement slightly more interesting.

Your manager wants only Accounts whose open Opportunity value is greater than ₹5,00,000.

We can use HAVING.

List<AggregateResult> results = [
    SELECT AccountId,
           SUM(Amount) totalAmount
    FROM Opportunity
    WHERE IsClosed = false
    AND AccountId != null
    GROUP BY AccountId
    HAVING SUM(Amount) > 500000
];

Remember the difference:

  • WHERE: Filters individual records before grouping.
  • HAVING: Filters grouped results after aggregation.

4. Semi-Joins and Anti-Joins

These are extremely useful features in advanced SOQL.

4.1 Semi-Join

A semi-join retrieves parent records that have matching child records.

Requirement: Retrieve Accounts that have at least one Contact.

List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Id IN (
        SELECT AccountId
        FROM Contact
    )
];

Here, Salesforce identifies Account IDs from Contact records and returns matching Accounts.

4.2 Anti-Join

An anti-join does the opposite. It retrieves parent records that don't have matching child records.

Requirement: Retrieve Accounts that don't have any Contacts.

List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Id NOT IN (
        SELECT AccountId
        FROM Contact
    )
];

This is particularly useful in data cleanup operations.

Developer Tip: SOQL semi-joins and anti-joins have restrictions. They cannot be used like unrestricted SQL joins. Check Salesforce SOQL limitations when combining multiple semi-join conditions.

5. Dynamic SOQL

Until now, we have written static SOQL queries.

But what happens when a user wants to search Accounts using different filters?

  • Search by Account Name.
  • Filter by Industry.
  • Filter by Billing Country.
  • Search using multiple conditions.

Writing a separate static query for every combination is not practical. Dynamic SOQL allows us to construct queries at runtime.

Example: Dynamic Account Search

public class AccountSearchService {

    public static List<Account> searchAccounts(
        String accountName,
        String industry
    ) {

        String query =
            'SELECT Id, Name, Industry, Phone ' +
            'FROM Account WHERE Id != null';

        if (String.isNotBlank(accountName)) {
            query += ' AND Name LIKE \'%' +
                String.escapeSingleQuotes(accountName) + '%\'';
        }

        if (String.isNotBlank(industry)) {
            query += ' AND Industry = \'' +
                String.escapeSingleQuotes(industry) + '\'';
        }

        return Database.query(query);
    }
}

This example demonstrates how a query can be constructed based on user input.

However, directly concatenating user input into a query can introduce SOQL injection vulnerabilities.

5.1 Safer Dynamic SOQL Using Bind Variables

A better approach is to use Database.queryWithBinds().

public class AccountSearchService {

    public static List<Account> searchAccounts(
        String accountName,
        String industry
    ) {

        String query =
            'SELECT Id, Name, Industry, Phone ' +
            'FROM Account WHERE Id != null';

        Map<String, Object> bindValues =
            new Map<String, Object>();

        if (String.isNotBlank(accountName)) {
            query += ' AND Name LIKE :accountName';

            bindValues.put(
                'accountName',
                '%' + accountName + '%'
            );
        }

        if (String.isNotBlank(industry)) {
            query += ' AND Industry = :industry';
            bindValues.put('industry', industry);
        }

        return Database.queryWithBinds(
            query,
            bindValues,
            AccessLevel.USER_MODE
        );
    }
}

This approach is safer because user-provided values are passed separately from the query string.

Important: Bind variables protect values, not dynamic object names, field names, or sort directions. Validate dynamic fields against an allowlist before adding them to the query.

6. SOQL Query Selectivity and Performance

Writing a query that works is one thing. Writing a query that performs well with millions of records is another.

Consider this query:

List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Name LIKE '%Salesforce%'
];

It may work perfectly in a development org with a few hundred Accounts. But the same query can become expensive when the org contains millions of records.

What Makes a Query Selective?

A selective query filters out enough records so that Salesforce doesn't need to scan a large portion of the table.

List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Name LIKE 'Tech%'
];

Practical Query Optimization Tips

1. Select only required fields

SELECT Id, Name, Industry
FROM Account

2. Avoid leading wildcards where possible

Prefer prefix searches such as LIKE 'Tech%' instead of LIKE '%Tech%'.

3. Use indexed fields appropriately

Fields such as record IDs, certain standard fields, and eligible custom fields may have indexes. However, indexing alone doesn't guarantee a selective query.

4. Avoid SOQL inside loops

Incorrect approach:

for (Contact con : contacts) {

    Account acc = [
        SELECT Id, Name
        FROM Account
        WHERE Id = :con.AccountId
    ];

}

Better approach:

Set<Id> accountIds = new Set<Id>();

for (Contact con : contacts) {
    if (con.AccountId != null) {
        accountIds.add(con.AccountId);
    }
}

Map<Id, Account> accountMap =
    new Map<Id, Account>([
        SELECT Id, Name
        FROM Account
        WHERE Id IN :accountIds
    ]);

This avoids executing a separate query for every Contact.

5. Use Query Plan

Salesforce provides a Query Plan tool in Developer Console and supported query editors. It helps you understand the available execution plans, index usage, estimated records, and query cost.

7. Practical Project: Retrieve Accounts with Contacts and Open Opportunity Summary

Now let's combine what we have learned.

Imagine you are developing a Sales Management application.

The business team wants an Account dashboard with the following information:

  1. Account Name.
  2. Account Industry.
  3. Related Contact Names.
  4. Total number of Contacts.
  5. Total open Opportunity value.
  6. Number of open Opportunities.

We can use relationship queries and aggregate queries together to achieve this.

Step 1: Create an Apex Wrapper Class

public class AccountSummaryWrapper {

    @AuraEnabled
    public Id accountId { get; set; }

    @AuraEnabled
    public String accountName { get; set; }

    @AuraEnabled
    public String industry { get; set; }

    @AuraEnabled
    public Integer totalContacts { get; set; }

    @AuraEnabled
    public Decimal openOpportunityValue { get; set; }

    @AuraEnabled
    public Integer openOpportunityCount { get; set; }

    @AuraEnabled
    public List<String> contactNames { get; set; }

    public AccountSummaryWrapper() {
        contactNames = new List<String>();
        totalContacts = 0;
        openOpportunityValue = 0;
        openOpportunityCount = 0;
    }
}

Step 2: Create Apex Service Class

We will use two queries:

  • One parent-to-child query to retrieve Accounts and Contacts.
  • One aggregate query to calculate open Opportunity values and counts.
public with sharing class AccountSummaryService {

    @AuraEnabled(cacheable=true)
    public static List<AccountSummaryWrapper> getAccountSummary() {

        Map<Id, AccountSummaryWrapper> summaryMap =
            new Map<Id, AccountSummaryWrapper>();

        // Query 1: Accounts and related Contacts
        List<Account> accounts = [
            SELECT Id,
                   Name,
                   Industry,
                   (SELECT Id, Name FROM Contacts)
            FROM Account
            WITH USER_MODE
            LIMIT 100
        ];

        for (Account acc : accounts) {

            AccountSummaryWrapper wrapper =
                new AccountSummaryWrapper();

            wrapper.accountId = acc.Id;
            wrapper.accountName = acc.Name;
            wrapper.industry = acc.Industry;
            wrapper.totalContacts = acc.Contacts.size();

            for (Contact con : acc.Contacts) {
                wrapper.contactNames.add(con.Name);
            }

            summaryMap.put(acc.Id, wrapper);
        }

        // Query 2: Aggregate open Opportunity details
        List<AggregateResult> opportunityResults = [
            SELECT AccountId,
                   SUM(Amount) totalAmount,
                   COUNT(Id) totalCount
            FROM Opportunity
            WHERE IsClosed = false
            AND AccountId IN :summaryMap.keySet()
            WITH USER_MODE
            GROUP BY AccountId
        ];

        for (AggregateResult ar : opportunityResults) {

            Id accountId = (Id) ar.get('AccountId');

            AccountSummaryWrapper wrapper =
                summaryMap.get(accountId);

            if (wrapper != null) {

                wrapper.openOpportunityValue =
                    (Decimal) ar.get('totalAmount');

                wrapper.openOpportunityCount =
                    (Integer) ar.get('totalCount');
            }
        }

        return summaryMap.values();
    }
}

Why Did We Use Separate Queries?

Because the Contact and Opportunity relationships are different, and we need both detailed Contact records and aggregated Opportunity values.

Combining these relationships into one query could introduce duplicate combinations of Contact and Opportunity records, making aggregate calculations incorrect.

This approach keeps the logic simple and avoids unnecessary queries inside loops.

Also, WITH USER_MODE enforces user-level data access for the SOQL queries. The with sharing declaration provides record-level sharing enforcement for the class.

Step 3: Expected Output

Suppose our Salesforce org contains the following data:

Account Contacts Open Opportunities Open Value
ABC Technologies 3 2 ₹8,00,000
XYZ Solutions 2 1 ₹3,50,000
Cloud Systems 5 4 ₹12,00,000

Our Apex service returns one summary wrapper per Account, including the related Contact names.

This data can be displayed in an LWC datatable or an Account dashboard.

Production Note: The example uses LIMIT 100 for demonstration. A production dashboard should implement pagination or an appropriate filtering strategy rather than silently limiting the result set. Also, consider child-record volume and pagination when retrieving Contacts.

8. Common Mistakes Developers Should Avoid

Common Mistake Better Approach
Writing SOQL inside loops Use collection-based queries
Retrieving unnecessary fields Select only required fields
Ignoring relationship names Verify child relationship API names
Using SOQL string concatenation for user input Use bind variables
Ignoring query selectivity Review Query Plan
Retrieving all records without pagination Use filters and pagination
Ignoring security in Apex queries Use USER_MODE where appropriate

9. Final Thoughts

SOQL is not just about retrieving records from Salesforce. Once you start working on enterprise-level applications, you need to understand how to retrieve related data, calculate summaries, filter records efficiently, and build queries dynamically.

In my experience, understanding the difference between relationship queries, aggregate queries, and semi-joins makes a big difference when designing Apex services.

You don't always need more SOQL queries to solve a requirement. Sometimes, a well-written query can replace a lot of unnecessary Apex code.

My suggestion to developers is simple: don't just focus on writing queries that return the expected result. Also understand how those queries behave when your Salesforce org has thousands or millions of records.

That is what separates basic SOQL knowledge from advanced SOQL development.

Practice Assignment

Try solving these requirements in your Salesforce Developer Org:

  1. Retrieve all Accounts with their related Contacts.
  2. Find Accounts having more than 5 Contacts.
  3. Calculate the total Opportunity amount for each Account.
  4. Retrieve Accounts that don't have any Opportunities.
  5. Retrieve Accounts having at least one Closed Won Opportunity.
  6. Build a dynamic Account search using Name, Industry, and Billing Country.
  7. Create an Apex method that returns Account summaries for an LWC dashboard.

Bonus Challenge: Build an LWC component that displays Account Name, Total Contacts, Open Opportunity Count, and Total Open Opportunity Value using the Apex service developed in this article.

Try implementing it yourself before looking for a solution. You will understand SOQL much better when you solve these requirements with actual Salesforce records.

About KhumedSFDC

KhumedSFDC is a Salesforce learning destination where I share practical Salesforce development concepts, Apex, Lightning Web Components, integrations, and real-world implementation scenarios.

If you are learning Salesforce development or preparing for a developer role, keep practicing with real project requirements.

Advanced Salesforce Development Learning Series

Article 1: Advanced Apex Programming – Reusable, Production-Ready Code

Article 2: Advanced SOQL – Relationships, Aggregates and Complex Filtering

Next Article: Advanced Apex Collections – Maps, Sets, Lists and Efficient Data Processing

Happy Learning & Happy Coding!
– Khumed Khatib | KhumedSFDC