Imagine you’re a Salesforce developer working for a business that wants to identify its most valuable customer the one that contributes the highest revenue. Whether it’s for internal reporting, executive dashboards, or high-touch account management, this kind of insight is gold.
In this post, we’ll walk through an Apex method that finds the Account with the highest Annual Revenue. It’s a simple, smart use of SOQL and Apex that can be added to dashboards, alerts, or even scheduled logic.
Perfect for developers who are just starting out with Apex and want to see how queries, conditions, and list handling work together in real business use cases.
🧠 What Are We Trying to Do?
We’re building a method that:
Queries Account records in Salesforce
Filters only those that have a non-null AnnualRevenue
Sorts them by AnnualRevenue in descending order
Returns the Account with the highest revenue
This is like asking Salesforce: “Show me the customer who brings in the most money.”
🔍 Code Explanation
public with sharing class ApexUseCaseTwentyFour {
public static Account findMaxRevenueGenerator(){
We start by declaring a class ApexUseCaseTwentyFour
and a public static method named findMaxRevenueGenerator
. This method will return a single Account
record.
List<Account> accRecords = [SELECT Id, Name
FROM Account
WHERE AnnualRevenue != null
ORDER BY AnnualRevenue DESC
LIMIT 1];
Let’s break this down:
We query the Account object.
Filter records where
AnnualRevenue
is not null.Sort by
AnnualRevenue
in descending order (highest first).Limit to just 1 record the top revenue account.
if(accRecords.size() == 1){
return accRecords[0];
}
return null;
}
}
If one record is returned, we return it. Otherwise, we return null
which covers cases where there are no accounts with revenue set.
It’s a simple pattern, but very effective.
✅ Why This Is Useful
This method gives you instant access to your top customer, which can be useful for:
Displaying on executive dashboards
Triggering alerts for special treatment or follow-ups
Creating leaderboards in revenue-focused apps
Want to expand it? You could:
Return the top 5 revenue accounts
Add fields like
Owner
,Phone
, orIndustry
in the queryUse it in a scheduled job to send daily reports
🧾 Final Code Snippet
public with sharing class ApexUseCaseTwentyFour {
public static Account findMaxRevenueGenerator(){
List<Account> accRecords = [SELECT Id, Name
FROM Account
WHERE AnnualRevenue != null
ORDER BY AnnualRevenue DESC
LIMIT 1];
if(accRecords.size() == 1){
return accRecords[0];
}
return null;
}
}
🎥 Watch It in Action!
Want to see how this works live in Developer Console? I’ve got you covered. Watch this short walkthrough to see how the top-revenue account is pulled instantly using this method.