Salesforce Object Query Language (SOQL) is a specialized query language used in Salesforce to query data from the Salesforce database. It is similar to SQL (Structured Query Language) but specifically designed for Salesforce's data model, which includes standard and custom objects.
Why Use SOQL?
Retrieve data efficiently from Salesforce objects.
Filter, sort, and aggregate data.
Used in Apex code, Visualforce, Lightning components, and APIs.
Fetch related records using relationship queries.
Best Practices for SOQL
Use SELECT only required fields to improve performance.
Apply WHERE conditions to filter data efficiently.
Use LIMIT to avoid large query results.
Optimize queries using indexes on frequently queried fields.
Avoid SOQL inside loops to prevent hitting governor limits.
Basic Syntax of SOQL
A simple SOQL query follows this structure:SELECT field1, field2 FROM ObjectName WHERE conditions ORDER BY field ASC/DESC LIMIT n
Examples of SOQL Queries
1. Basic QuerySELECT Name, Industry FROM AccountThis retrieves the Name and Industry fields from the Account object.2. Query with FilteringSELECT Name, Phone FROM Contact WHERE LastName = 'Smith'This fetches all contacts with the last name "Smith."3. Using Logical OperatorsSELECT Name FROM Account WHERE Industry = 'Technology' AND AnnualRevenue > 1000000This retrieves accounts in the "Technology" industry with annual revenue greater than 1,000,000.4. Ordering ResultsSELECT Name, CreatedDate FROM Opportunity ORDER BY CreatedDate DESCThis fetches opportunities sorted by the creation date in descending order.5. Limiting the ResultsSELECT Name FROM Lead ORDER BY CreatedDate DESC LIMIT 10This fetches the latest 10 leads.
Relationship Queries
1. Child-to-Parent Query (Using Dot Notation)
SELECT Name, Account.Name FROM ContactThis retrieves contacts and their related account names.
2. Parent-to-Child Query (Using Subquery)
SELECT Name, (SELECT LastName FROM Contacts) FROM AccountThis retrieves accounts and all associated contacts.
Aggregate Functions in SOQL
SOQL supports aggregate functions like COUNT, SUM, MIN, MAX, and AVG.
Example:
SELECT COUNT(Id) FROM Account WHERE Industry = 'Technology'This returns the number of accounts in the Technology industry.
SOQL in Apex
SOQL is commonly used in Apex to interact with Salesforce data.
Example in Apex:
List<Account> accList = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'];for(Account acc : accList) { System.debug(acc.Name);}This Apex code retrieves accounts in the Technology industry and prints their names in the debug log.