Understanding SOQL: The Salesforce Query Language

Introduction
What is SOQL?
SOQL stands for “Salesforce Object Query Language ”.
It’s very similar to SQL (Structured Query Language), but it is designed specifically for Salesforce data.
Instead of accessing tables (like SQL), SOQL works with Salesforce Objects like Account, Contact, Lead, Opportunity).
Why do we use SOQL?
- To fetch data from Salesforce objects.
- To get only the fields and records you need (instead of loading everything).
- In short: SOQL helps you talk to Salesforce’s database to pull the exact data you need.
Basic Syntax & Clauses
[SELECT Name, Industry FROM Account WHERE Industry = ‘Technology’]
- Clause (SELECT) => This tells Salesforce what fields you want to fetch.
-> Here, I am saying: “I want Name and Industry fields.” - Clause (FROM) => This tells SOQL which object/table you are querying.
-> Here, Account = Salesforce object where data is stored - Clause (WHERE) =>WHERE is used to filter records.
-> You don’t want all accounts, only those where the Industry field has the value Technology.
It’s like saying: “Give me only Accounts where industry is Technology.”
Common Operators
- Equality & Inequality: = (equal to), != (not equal to)
= (equal to) => [SELECT Name FROM Account WHERE Industry = ‘Banking’]
!= (not equal to)=> [SELECT Name FROM Account WHERE Industry != ‘Finance’] - Comparison: (greater than >), (less than < ), (greater than or equal => )
[SELECT Name, Amount FROM Opportunity WHERE Amount > 50000] - Text Matching: ( LIKE → partial text match (use % as wildcard) )
[ SELECT Name FROM Contact WHERE LastName LIKE ‘Patel%’ ]
Sorting & Limiting Results
- Sorting (ORDER BY): – Can be ascending (ASC) or descending (DESC).
ASC = [ SELECT Name, Industry FROM Account ORDER BY Name ASC ]
DESC = [ SELECT Name, Amount FROM Opportunity ORDER BY Amount DESC ] - Limit Results (LIMIT): – ( Restricts the number of rows returned )
[ SELECT id, Name FROM Account LIMIT 5 ] - OFFSET (Skip Records) : Used along with LIMIT to skip a certain number of rows before returning results.
[ SELECT Name FROM Account ORDER BY Name ASC LIMIT 5 OFFSET 5]
Breakdown:- LIMIT 5 = give me only 5 rows,OFFSET 5 = start after the first 5 records.
Relationship Queries
SOQL supports relationship navigation in two directions:
- 1. Child-to-Parent: – Using (Dot notation)
[ SELECT LastName, Account.Name FROM Contact ] - 2. Parent-to-Child: – Using (Subquery)
[SELECT Name, (SELECT LastName FROM Contacts) FROM Account]
Aggregate Functions
What are Aggregate Functions
Aggregate functions let you summarize data instead of fetching individual records.
They are useful when you need counts, totals, averages, minimums, or maximums of values.
In SOQL, aggregate functions are often used with GROUP BY and HAVING.
Supported Aggregate Functions in SOQL
- COUNT():-
Returns the number of rows.
Example: Count Contacts grouped by Account
[ SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId ] - GROUP BY:-
Example: Count Opportunities per Stage
[ SELECT StageName, COUNT(Id) FROM Opportunity GROUP BY StageName ] - SUM() :-
Returns the total of numeric fields.
Example: (Sum of Opportunity Amounts)
[SELECT SUM(Amount) FROM Opportunity WHERE StageName = ‘Closed Won’] - AVG() :-
Returns the average value of a numeric field.
Example: (Average Opportunity Amount)
[SELECT AVG(Amount) FROM Opportunity WHERE StageName = ‘Closed Won’]
Practical Example
Below are concrete examples and short explanations to demonstrate common tasks:
- Retrieve opportunities above a threshold:
[ SELECT Name, StageName, Amount FROM Opportunity WHERE Amount > 100000 ORDER BY Amount DESC ] - Get accounts with their contacts (parent-to-child):
[ SELECT Name, (SELECT FirstName, LastName FROM Contacts ORDER BY LastName) FROM Account WHERE BillingCountry = ‘India’ ] - Count active users or records:
[ SELECT COUNT(Id) FROM Contact WHERE IsDeleted = false ]
SOQL vs SQL — Key Differences
-
Purpose
SQL (Structured Query Language>)→> General-purpose query language used in relational databases like MySQL, Oracle, PostgreSQL.
SOQL (Salesforce Object Query Language) → Salesforce-specific query language used to retrieve records from Salesforce objects. -
Operations Supported
SQL → >Supports SELECT, INSERT, UPDATE, DELETE, CREATE TABLE, and many other commands. It is used for both data queries and data manipulation in relational databases.
SOQL → Supports only SELECT queries. You cannot directly insert, update, or delete records using SOQL; those operations are handled through Apex DML statements instead. -
Data Model
SQL →> Works with tables & rows in a relational database.
SOQL → Works with Salesforce objects & records (like Account, Contact, Opportunity).
Best Practices for Performance
- Use selective WHERE filters (prefer indexed fields like Id, CreatedDate, or custom indexed fields).
- Avoid returning unnecessary fields — query only what you need.
- Use LIMIT and OFFSET judiciously — OFFSET can be expensive for large offsets.
- Prefer relationships that are indexed or use SOSL when searching across multiple fields.
- Avoid queries inside loops in Apex (bulkify your code).
Tips & Common Pitfalls
- Be careful with NULL handling — compare fields explicitly where needed.
- LIKE ‘text%’ is supported; using leading wildcards (e.g., ‘%text’) may prevent index usage.
- Field-level security and sharing rules still apply when you query in Apex with ‘WITH SECURITY_ENFORCED’ if required.
- Monitor query selectivity using Salesforce query plans in the Developer Console.
Conclusion
SOQL is a simple yet powerful tool for extracting data from Salesforce. By writing selective queries, understanding object relationships, and following best practices, you can create efficient Apex code and avoid common performance issues. Use the provided examples as a foundation and adapt them to suit your organization’s specific data requirements. If you’re looking to implement advanced Salesforce solutions or need expert support, partnering with a trusted Salesforce development company in USA can help you get the most out of your Salesforce platform.
related blog
