Salesforce SOQL Queries – A Complete Guide with Real Examples

Salesforce SOQL Queries – A Complete Guide with Real Examples


🧠 Introduction

As a Salesforce Developer, SOQL (Salesforce Object Query Language) is your best friend. Whether you’re building Apex classes, triggers, LWC components, or batch jobs — you’ll need SOQL to fetch and manipulate Salesforce data efficiently.

SOQL looks similar to SQL but is optimized for Salesforce’s object-based data model. In this blog, we’ll walk through every type of SOQL query — from basic to advanced — with real-world examples and developer tips to help you write clean, efficient, and governor-limit-friendly queries.


⚙️ What is SOQL?

SOQL stands for Salesforce Object Query Language.
It’s used to fetch data from Salesforce objects (both standard and custom) like Account, Contact, Opportunity, or CustomObject__c.

Syntax:

SELECT fieldList FROM ObjectName WHERE conditions ORDER BY fields LIMIT number

1. Basic SOQL Query

Use this to fetch specific fields from an object.

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

Output: Returns all Accounts with their Id, Name, and Industry.

💡 Pro Tip: Always fetch only the required fields — it saves heap space and improves performance.


2. Filtered SOQL Query (Using WHERE Clause)

Filters help you retrieve only relevant records.

List<Contact> cons = [SELECT Id, Name, Email FROM Contact WHERE LastName = 'Bansal'];

You can also use multiple conditions:

SELECT Id, Name FROM Account WHERE Industry = 'Technology' AND Rating = 'Hot'

3. Using Comparison & Logical Operators

SOQL supports operators like =, !=, <, >, <=, >=, LIKE, IN, NOT IN, and INCLUDES.

Example 1:

SELECT Id, Name FROM Opportunity WHERE Amount > 50000

Example 2 (LIKE & Wildcards):

SELECT Id, Name FROM Account WHERE Name LIKE 'A%'

🔹 Fetches all accounts starting with the letter A.


4. Relationship Queries (Parent-to-Child & Child-to-Parent)

🧭 Child-to-Parent (Inner Query)

Use dot notation to fetch parent fields from a child object.

SELECT Id, Name, Account.Name, Account.Industry FROM Contact

Parent-to-Child (Subquery)

Use subqueries to fetch related child records.

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

💡 Use Case: Fetch Accounts with their associated Contacts.


5. Aggregate SOQL Queries (COUNT, SUM, AVG, MIN, MAX)

Used for reporting or analytics directly in Apex.

SELECT COUNT(Id) FROM Account WHERE Industry = 'Banking'

Other examples:

SELECT SUM(Amount), MAX(Amount), MIN(Amount), AVG(Amount) FROM Opportunity

Grouping Example:

SELECT Rating, COUNT(Id) FROM Account GROUP BY Rating

Output: Shows how many accounts exist under each Rating (Hot, Warm, Cold).


6. SOQL with NOT IN Operator

Fetch records not associated with a related record.

SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Contact)

✅ Fetches all Accounts that have no Contacts.


7. Using LIMIT and OFFSET (Pagination or Specific Ranking)

LIMIT restricts the number of records.
OFFSET skips a certain number of records.

Example: Fetch the second highest Annual Revenue account.

SELECT Id, Name, AnnualRevenue FROM Account
WHERE AnnualRevenue != null
ORDER BY AnnualRevenue DESC
LIMIT 1 OFFSET 1

 8. Enforcing Field-Level Security in SOQL

Use WITH USER_MODE or WITH SYSTEM_MODE to control FLS enforcement.

List<Account> accs = [SELECT Id, Name FROM Account WITH USER_MODE];
  • USER_MODE: Enforces field & object permissions.

  • SYSTEM_MODE: Runs with admin privileges (ignores user FLS).


9. Dynamic SOQL (Runtime Query Building)

When you need to build queries dynamically (for example, filters chosen by users):

String industryType = 'Banking';
List<Account> accList = Database.query('SELECT Id, Name FROM Account WHERE Industry = \'' + industryType + '\'');

✅ Useful for search features or configurable queries.


10. Using IN Operator

List<String> industries = new List<String>{'Banking', 'Finance'};
List<Account> accs = [SELECT Id, Name FROM Account WHERE Industry IN :industries];

11. SOQL in AggregateResult (for Custom Calculations)

To fetch results into a list of AggregateResult objects:

List<AggregateResult> results = [
SELECT COUNT(Id) countAcc, Industry FROM Account GROUP BY Industry
];

for (AggregateResult ar : results) {
System.debug('Industry: ' + ar.get('Industry') + ' Count: ' + ar.get('countAcc'));
}


12. Nested Aggregate Query (GROUP BY with ROLLUP)

Used for hierarchical summaries.

SELECT Industry, Rating, COUNT(Id)
FROM Account
GROUP BY ROLLUP(Industry, Rating)

Use Case: Get totals per Rating and per Industry, plus overall total.


13. SOQL with ORDER BY Clause

Sorting your results by a specific field.

SELECT Id, Name FROM Account ORDER BY CreatedDate DESC

You can also sort by multiple fields:

SELECT Id, Name FROM Contact ORDER BY LastName ASC, FirstName DESC

14. SOQL with FOR UPDATE (Locking Records)

Used to prevent race conditions when multiple transactions try to update the same record.

List<Account> accs = [SELECT Id, Name FROM Account WHERE Name = 'SalesforceGeek' FOR UPDATE];

✅ Locks those records until the transaction completes.


15. SOSL vs SOQL (Quick Comparison)

Feature SOQL SOSL
Purpose Query specific object Search text across multiple objects
Syntax SELECT ... FROM ... FIND 'keyword' IN ALL FIELDS RETURNING ...
Use Case Structured data retrieval Global search

Example:

List<List<SObject>> searchList = [FIND 'Kashish' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)];

16. Real-Life Example – Update Account Contact Count (Aggregate SOQL)

List<AggregateResult> aggList =
[
SELECT Count(Id) countId, AccountId
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];
for (AggregateResult agg : aggList)
{
Account acc = new Account(
Id = (Id)agg.get('AccountId'),
No_of_Contact__c = (Double)agg.get('countId')
);
accountsToUpdate.add(acc);
}
update accountsToUpdate;

17. SOQL Query Limits

Limit Type Maximum
Records retrieved per query 50,000
Total SOQL queries per transaction 100 (sync) / 200 (async)
Query rows in Batch Apex 50 million
DML statements per transaction 150

💡 Pro Tip: Always bulkify your code and avoid SOQL inside loops!


18. Common SOQL Interview Scenarios

Q1: Fetch top 5 Opportunities by Amount.

SELECT Id, Name, Amount FROM Opportunity ORDER BY Amount DESC LIMIT 5

Q2: Fetch Accounts with no Opportunities.

SELECT Id, Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Opportunity)

Q3: Fetch number of Contacts per Account.

SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId

Conclusion

Mastering SOQL is non-negotiable for every Salesforce Developer.
From simple data fetches to complex aggregations, SOQL helps you interact with Salesforce data efficiently — but remember to always respect governor limits, bulkify your code, and fetch only what you need.

Whether you’re preparing for an interview or building a scalable enterprise solution — mastering these SOQL patterns will make your Apex logic clean, fast, and powerful.

Leave a Comment

Your email address will not be published. Required fields are marked *