Advanced SOQL & SOSL
Aggregate Queries
What Are Aggregate Queries?
Aggregate queries are used to calculate values like totals, counts, averages, minimums, and maximums.
Simple Explanation
Instead of reading every record, ask Salesforce to do the math for you.
Common Aggregate Functions
-
COUNT() -
SUM() -
AVG() -
MIN() -
MAX()
Real-Life Example
“How many contacts do we have?”
SELECT COUNT(Id) FROM Contact
Grouping Data (GROUP BY)
Find total revenue per industry.
SELECT Industry, SUM(AnnualRevenue) FROM Account GROUP BY Industry
Using AggregateResult in Apex
AggregateResult[] results = [
SELECT Industry, SUM(AnnualRevenue) total
FROM Account
GROUP BY Industry
];
for (AggregateResult ar : results) {
System.debug(ar.get('Industry') + ' : ' + ar.get('total'));
}
Gist (Quick Revision)
Aggregate queries let Salesforce calculate totals and counts efficiently.
Dynamic SOQL & SOSL
What Is Dynamic SOQL?
Dynamic SOQL allows you to build queries at runtime using strings.
When to Use It
-
Search screens
-
Optional filters
-
User-driven conditions
Real-Life Example
A search page where filters change dynamically.
Dynamic SOQL Example
String industry = 'IT'; String query = 'SELECT Name FROM Account WHERE Industry = :industry'; List<Account> accounts = Database.query(query);
What Is SOSL?
SOSL (Salesforce Object Search Language) is used to search text across multiple objects.
Simple Explanation
SOQL = database query
SOSL = global search
SOSL Example
List<List<SObject>> results = [
FIND 'Alex*' IN ALL FIELDS
RETURNING Account(Name), Contact(LastName)
];
Gist (Quick Revision)
-
Dynamic SOQL builds queries at runtime
-
SOSL searches across multiple objects
SOQL & SOSL Performance Optimization
Why Performance Matters
Salesforce enforces governor limits, so inefficient queries can break your code.
Best Practices for Performance
1. Query Only Required Fields
❌ Bad
SELECT * FROM Account
✅ Good
SELECT Name FROM Account
3. Avoid SOQL in Loops
Use collections and maps instead.
4. Use Relationship Queries
One query is better than many.
Career Coach Insight
Performance questions are very common in interviews.
Interviewers want to hear:
“I avoid SOQL in loops and use aggregate queries where possible.”
Gist (Quick Revision)
Efficient queries save governor limits and improve scalability.
