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:
1. Basic SOQL Query
Use this to fetch specific fields from an object.
✅ 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.
You can also use multiple conditions:
3. Using Comparison & Logical Operators
SOQL supports operators like =, !=, <, >, <=, >=, LIKE, IN, NOT IN, and INCLUDES.
Example 1:
Example 2 (LIKE & Wildcards):
🔹 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.
Parent-to-Child (Subquery)
Use subqueries to fetch related child records.
💡 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.
Other examples:
Grouping Example:
✅ 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.
✅ 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.
8. Enforcing Field-Level Security in SOQL
Use WITH USER_MODE or WITH SYSTEM_MODE to control FLS enforcement.
-
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):
✅ Useful for search features or configurable queries.
10. Using IN Operator
11. SOQL in AggregateResult (for Custom Calculations)
To fetch results into a list of AggregateResult objects:
12. Nested Aggregate Query (GROUP BY with ROLLUP)
Used for hierarchical summaries.
✅ 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.
You can also sort by multiple fields:
14. SOQL with FOR UPDATE (Locking Records)
Used to prevent race conditions when multiple transactions try to update the same record.
✅ 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:
16. Real-Life Example – Update Account Contact Count (Aggregate SOQL)
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.
Q2: Fetch Accounts with no Opportunities.
Q3: Fetch number of Contacts per Account.
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.

