
As we conclude our journey through the world of SOQL, it’s time to put your knowledge into action with real-world use cases and examples. In this chapter, we’ll explore practical scenarios where SOQL plays a crucial role in solving business challenges and extracting meaningful insights from your Salesforce data. By diving into these use cases, you’ll gain a deeper understanding of how to apply SOQL in different contexts and unlock its full potential.
Use Case 1: Sales Performance Analysis
Imagine you’re a sales manager who wants to analyze the performance of your sales team. You need to retrieve data on opportunities, such as the total number of closed deals, the average deal amount, and the top salespeople. SOQL enables you to retrieve this information efficiently:
<strong>// Total closed deals</strong>
Decimal totalClosedDeals = [SELECT COUNT() FROM Opportunity WHERE IsClosed = TRUE];
<strong>// Average deal amount</strong>
AggregateResult avgDealAmountResult = [SELECT AVG(Amount) FROM Opportunity WHERE IsClosed = TRUE];
Decimal avgDealAmount = (Decimal) avgDealAmountResult.get('expr0');
<strong>// Top salespeople</strong>
List<AggregateResult> topSalespeopleResult = [SELECT Owner.Name, SUM(Amount) totalAmount
FROM Opportunity
WHERE IsClosed = TRUE
GROUP BY OwnerId, Owner.Name
ORDER BY totalAmount DESC
LIMIT 5];
In this example, you’re using SOQL to calculate key metrics and identify the top performers within your sales team.
Use Case 2: Customer Support Insights
As a customer support manager, you’re interested in understanding support case trends to improve service quality. You want to retrieve data on case volume, average response time, and common issue categories. SOQL allows you to gather this information effectively:
<strong>// Case volume by status</strong>
List<AggregateResult> caseVolumeByStatus = [SELECT Status, COUNT(Id) numCases
FROM Case
GROUP BY Status];
<strong>// Average response time</strong>
AggregateResult avgResponseTimeResult = [SELECT AVG(Response_Time__c) FROM Case];
<strong>// Common issue categories</strong>
List<AggregateResult> commonIssuesResult = [SELECT Subject, COUNT(Id) numCases
FROM Case
GROUP BY Subject
ORDER BY numCases DESC
LIMIT 3];
With SOQL, you’re able to analyze case data and gain insights that can inform your support strategy.
Use Case 3: Marketing Campaign Effectiveness
As a marketing analyst, you’re tasked with evaluating the effectiveness of your recent email marketing campaign. You want to assess the open and click-through rates for different email templates. SOQL enables you to gather this information efficiently:
<strong>// Open rates by template</strong>
List<AggregateResult> openRatesByTemplate = [SELECT Email_Template__c, AVG(Open_Rate__c) avgOpenRate
FROM Email_Interaction__c
GROUP BY Email_Template__c];
<strong>// Click-through rates by template</strong>
List<AggregateResult> clickThroughRatesByTemplate = [SELECT Email_Template__c, AVG(Click_Through_Rate__c) avgClickThroughRate
FROM Email_Interaction__c
GROUP BY Email_Template__c];
By leveraging SOQL, you’re able to analyze engagement metrics and gain insights into the effectiveness of your marketing campaigns.
Use Case 4: Forecasting Inventory Needs
Suppose you manage inventory for a retail business and need to forecast inventory needs based on historical sales data. You want to retrieve the top-selling products and their quantities sold. SOQL enables you to retrieve this information efficiently:
<strong>// Top-selling products and quantities sold</strong>
List<AggregateResult> topSellingProducts = [SELECT Product__c, SUM(Quantity__c) totalQuantity
FROM Sales_Transaction__c
GROUP BY Product__c
ORDER BY totalQuantity DESC
LIMIT 10];
Using SOQL, you’re able to identify the most popular products and plan your inventory accordingly.
Following are some queries that you can try:
Query 1: Retrieve Accounts with related Contacts and Opportunities
SELECT Id, Name, (SELECT Id, FirstName, LastName FROM Contacts), (SELECT Id, Name FROM Opportunities) FROM Account
Explanation: This query retrieves Account records along with their related Contacts and Opportunities using nested subqueries.
Query 2: Find Opportunities with Close Dates in the Next 30 Days
SELECT Id, Name, CloseDate FROM Opportunity WHERE CloseDate = NEXT_N_DAYS:30
Explanation: This query fetches Opportunity records where the Close Date falls within the next 30 days.
Query 3: Get Leads Created in the Last 7 Days
SELECT Id, Name, CreatedDate FROM Lead WHERE CreatedDate = LAST_N_DAYS:7
Explanation: This query retrieves Lead records that were created within the last 7 days.
Query 4: Retrieve Contacts without an Account
SELECT Id, FirstName, LastName FROM Contact WHERE AccountId = NULL
Explanation: This query retrieves Contact records that are not associated with any Account.
Query 5: Find the Total Amount of Opportunities for each Stage
SELECT StageName, SUM(Amount) FROM Opportunity GROUP BY StageName
Explanation: This query groups Opportunities by their Stage Name and calculates the total amount for each stage.
Query 6: Get the Top 5 Opportunities by Amount
SELECT Id, Name, Amount FROM Opportunity ORDER BY Amount DESC LIMIT 5
Explanation: This query retrieves the top 5 Opportunities with the highest Amount values, ordered in descending order.
Query 7: Retrieve Accounts and Contacts where Account Name matches Contact First Name
SELECT Id, Name, (SELECT Id, FirstName FROM Contacts WHERE Account.Name = FirstName) FROM Account
Explanation: This query fetches Account records along with related Contacts where the Account Name matches the Contact’s First Name.
Query 8: Find Opportunities without Activities
SELECT Id, Name FROM Opportunity WHERE Id NOT IN (SELECT WhatId FROM Activity)
Explanation: This query retrieves Opportunities without related Activities.
Query 9: Retrieve Contacts with Email and Phone not on the same record
SELECT Id, FirstName, LastName, Email, Phone FROM Contact WHERE (Email != NULL AND Phone = NULL) OR (Email = NULL AND Phone != NULL)
Explanation: This query fetches Contact records where Email and Phone are not both present on the same record.
Query 10: Get Opportunities with a Probability over 70% and Amount over $10,000
SELECT Id, Name, Amount, Probability FROM Opportunity WHERE Probability > 70 AND Amount > 10000
Explanation: This query retrieves Opportunities with a Probability greater than 70% and an Amount exceeding $10,000.
Query 11: Retrieve Contacts and their Account Billing Country
SELECT Id, FirstName, LastName, Account.Name, Account.BillingCountry FROM Contact
Explanation: This query retrieves Contact records along with their related Account’s Name and Billing Country.
Query 12: Get Leads Converted in the Last 3 Months
SELECT Id, Name, ConvertedDate FROM Lead WHERE IsConverted = true AND ConvertedDate = LAST_N_MONTHS:3
Explanation: This query fetches converted Lead records where the conversion occurred within the last 3 months.
Query 13: Find Opportunities with a Primary Campaign and Campaign Type
SELECT Id, Name, Campaign.Name, Campaign.Type FROM Opportunity WHERE CampaignId != NULL
Explanation: This query retrieves Opportunity records with their associated Campaign’s Name and Type.
Query 14: Retrieve Users with the Highest Number of Closed Won Opportunities
SELECT OwnerId, Owner.Name, COUNT(Id) FROM Opportunity WHERE StageName = 'Closed Won' GROUP BY OwnerId, Owner.Name ORDER BY COUNT(Id) DESC LIMIT 5
Explanation: This query returns the top 5 Users with the highest count of Closed Won Opportunities, ordered by the count in descending order.
Query 15: Get Contacts with duplicate Email addresses
SELECT Id, Email, COUNT(Id) FROM Contact GROUP BY Email HAVING COUNT(Id) > 1
Explanation: This query identifies Contact records with duplicate Email addresses.
Query 16: Retrieve Opportunities with the Highest Amount in each Stage
SELECT Id, Name, StageName, Amount FROM Opportunity WHERE (StageName, Amount) IN (SELECT StageName, MAX(Amount) FROM Opportunity GROUP BY StageName)
Explanation: This query fetches Opportunities with the highest Amount for each StageName.
Query 17: Find Accounts with Opportunities Created by a specific User
SELECT Id, Name FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE CreatedById = '005XXXXXXXXXXXXXXX')
Explanation: This query retrieves Account records with Opportunities created by a specific User.
Query 18: Get Cases with the Longest Time since Last Activity
SELECT Id, CaseNumber, LastModifiedDate, (SELECT Id, ActivityDate FROM CaseHistories ORDER BY ActivityDate DESC LIMIT 1) FROM Case WHERE LastModifiedDate = LAST_N_DAYS:365 ORDER BY LastModifiedDate ASC
Explanation: This query retrieves Case records modified in the last year along with their latest Case History activity.
Query 19: Retrieve Opportunities related to Contacts where Account Industry is ‘Technology’
SELECT Id, Name, (SELECT Id, FirstName FROM Contacts WHERE Account.Industry = 'Technology') FROM Opportunity
Explanation: This query fetches Opportunity records related to Contacts whose associated Account’s Industry is ‘Technology’.
Query 20: Find Accounts with no Open Opportunities
SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Opportunity WHERE IsClosed = false)
Explanation: This query identifies Account records with no open Opportunities.
Conclusion
Congratulations! You’ve now explored a variety of real-world use cases and examples that showcase the practical applications of SOQL in different business scenarios. These examples highlight how SOQL can be leveraged to analyze sales performance, gain customer support insights, assess marketing campaign effectiveness, and forecast inventory needs.
By studying these use cases, you’ve gained insights into how SOQL can be tailored to address specific business challenges and extract valuable insights from your Salesforce data. As you continue your journey with SOQL, remember that its versatility and power make it a valuable tool for data retrieval, manipulation, and analysis in various contexts.
As we conclude this guide, take these real-world use cases as inspiration for applying your SOQL skills in your own projects and scenarios. Continue to explore, experiment, and refine your abilities, and always strive to use SOQL effectively to derive meaningful insights and drive informed decision-making within your Salesforce environment.

About the blog
SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:
Newsletter
Subscribe to our email newsletter to be notified when a new post is published.