Ask Krrish Contact
Home
Developer & Admin
Apex Triggers Mastery Asynchronous Apex SOQL & SOSL Governor Limits Flows & Process Builder
Advanced Topics
LWC Essentials Security & Sharing Managed Packages Deployment & CI/CD Integration Patterns
Interview Prep
Practice interview questions
Resources
Sales Cloud Class Diagram
Blog AI News
Available Now
Agentforce Pricing Calculator New Debug Log Analyzer SFX Forge New SFX Grove SFX Travel Manager
Salesforce + AI
AI Agent Development Salesforce Agentforce Development Custom RAG Solutions AI + Salesforce Integration Customer Support AI Agents AI Lead Qualification AI Knowledge Base Assistant AI Workflow Automation
Salesforce work
Issue Fix Sprint Automation Sprint LWC & integrations Overflow support for partners Agentforce & AI usage review All services →
About Ask Krrish Contact

SOQL and SOSL: Complete Guide with Examples and Interview Questions

Unlock the power of data retrieval in Salesforce! This module covers the fundamentals of SOQL (Salesforce Object Query Language) and SOSL (Salesforce Object Search Language), essential tools for developers to interact with the Salesforce database.

Need hands-on help?

What is the difference between SOQL and SOSL?

SOQL queries one object and its related objects when you know where the data lives, and supports filters, relationships and aggregates. SOSL runs a text search across many objects at once using the search index and returns a list of lists, one per object. Use SOSL when a user types a term and you don't know which object holds it.

  • SOQL: 100 queries per synchronous transaction (200 async) and 50,000 rows in total.
  • SOSL: 20 searches per transaction and 2,000 rows per search.
  • Use bind variables, never string concatenation, to prevent SOQL injection.
  • Add WITH USER_MODE to enforce the running user's object, field and sharing access.
  • Filter on indexed fields so queries stay selective on large objects.

1. Introduction to SOQL & SOSL

In Salesforce development, interacting with data stored in your organization's database is fundamental. Unlike traditional SQL databases, Salesforce uses its own query languages tailored for its unique object model:

  • SOQL (Salesforce Object Query Language): Used to query a single sObject or multiple related sObjects. Similar to the SELECT statement in SQL.
  • SOSL (Salesforce Object Search Language): Used to perform text-based searches across multiple sObjects, returning results that match a search term. Similar to a search engine query.

Why are SOQL & SOSL Essential?

  • Data Retrieval: Get the exact data you need from Salesforce objects.
  • Automation: Power your Apex triggers, classes, Visualforce pages, and Lightning Components with dynamic data.
  • Business Logic: Implement complex business rules that depend on querying existing data.
  • Reporting & Dashboards: Understanding SOQL helps you comprehend how reports and list views fetch data.

Key Differences

  • SOQL: Best for retrieving specific data from a known object (or related objects) when you know the structure and specific fields — like looking up an address in a phone book by name.
  • SOSL: Best for searching text across multiple objects and fields when you don't know which object contains the data — like searching a keyword on the internet.

Both query languages are subject to Salesforce's governor limits to ensure efficient use of shared resources.

2. SOQL Basics

SOQL queries are used in Apex, Visualforce controllers, Lightning components, and the Developer Console. The result depends on the query and how it is assigned in Apex.

Basic Syntax

SOQL — Basic Syntax
SELECT FieldName1, FieldName2
FROM   ObjectApiName
[WHERE Conditions]
[ORDER BY FieldName [ASC|DESC]]
[LIMIT Number]
[OFFSET Number]
  • SELECT: Specifies the fields to retrieve — standard fields, custom fields ending in __c, and relationship fields.
  • FROM: The sObject to query (e.g., Account, Contact, MyCustomObject__c).
  • WHERE: Filters records using operators like =, !=, LIKE, IN, NOT IN, AND, OR.
  • ORDER BY: Sorts results. ASC (default) or DESC.
  • LIMIT: Restricts the number of rows returned.
  • OFFSET: Skips a specified number of rows — used for pagination.

Examples

SOQL — Account Names and Industries
SELECT Name, Industry FROM Account
SOQL — Contacts in San Francisco
SELECT Id, FirstName, LastName, Email
FROM Contact
WHERE MailingCity = 'San Francisco'
SOQL — Accounts Created in Last 30 Days
SELECT Id, Name, CreatedDate
FROM Account
WHERE CreatedDate = LAST_N_DAYS:30
ORDER BY Name ASC
LIMIT 10
SOQL — Closed Won Opportunities of $10k or More
SELECT Name, StageName, Amount
FROM Opportunity
WHERE StageName = 'Closed Won' AND Amount >= 10000
ORDER BY Amount DESC

Using SOQL in Apex

In Apex, embed SOQL queries directly within square brackets []. The return type depends on the query and assignment: a query can be assigned to a list, a single sObject, or an Integer for COUNT().

Apex — SOQL in Code
List<Account> topAccounts = [
    SELECT Id, Name, AnnualRevenue
    FROM Account
    ORDER BY AnnualRevenue DESC NULLS LAST
    LIMIT 5
];

for (Account acc : topAccounts) {
    System.debug('Account: ' + acc.Name + ', Revenue: ' + acc.AnnualRevenue);
}

// Use a list when no matching record is a valid outcome.
List<Account> matches = [
    SELECT Id, Name FROM Account WHERE Name = 'Acme Corp' LIMIT 1
];
if (matches.isEmpty()) {
    System.debug('No matching account found.');
} else {
    Account singleAccount = matches[0];
    System.debug('Found account: ' + singleAccount.Name);
}

3. SOQL Relationship Queries

Salesforce's relational data model allows you to query related records directly within SOQL — reducing the number of queries needed and helping stay within governor limits.

Parent-to-Child (Nested Subquery)

Query child records from a parent object using a subquery in the SELECT clause. The relationship name is typically the plural of the child object (e.g., Contacts for Contact records related to Account).

SOQL — Parent-to-Child Subquery
SELECT Id, Name, (SELECT Id, FirstName, LastName FROM Contacts)
FROM Account
Apex — Iterating Child Records
List<Account> accountsWithContacts = [
    SELECT Id, Name, (SELECT Id, FirstName, LastName, Email FROM Contacts)
    FROM Account
    WHERE Name LIKE 'ABC%'
];

for (Account acc : accountsWithContacts) {
    System.debug('Account: ' + acc.Name);
    if (acc.Contacts != null) {
        for (Contact con : acc.Contacts) {
            System.debug('  Contact: ' + con.FirstName + ' ' + con.LastName);
        }
    }
}

Child-to-Parent (Dot Notation)

Query fields from a parent object by traversing the relationship using dot notation. For custom relationships, use __r instead of __c (e.g., MyCustomLookup__r.Name).

SOQL — Child-to-Parent Traversal
SELECT Id, Name, Account.Name, Account.Industry
FROM Contact
WHERE Account.Industry = 'Technology'
Apex — Accessing Parent Fields
List<Contact> techContacts = [
    SELECT Id, FirstName, LastName, Account.Name, Account.Industry
    FROM Contact
    WHERE Account.Industry = 'Technology'
];

for (Contact con : techContacts) {
    System.debug('Contact: ' + con.FirstName + ' ' + con.LastName);
    if (con.Account != null) { // Always null-check parent relationships
        System.debug('  Account: ' + con.Account.Name + ' (' + con.Account.Industry + ')');
    }
}

4. SOQL Aggregate Functions & Grouping

SOQL supports aggregate functions to perform calculations across a set of records. These are commonly used with GROUP BY to group results by a specific field.

Common Aggregate Functions

  • COUNT() — Number of rows.
  • COUNT(FieldName) — Rows where the field is not null.
  • COUNT_DISTINCT(FieldName) — Unique non-null values.
  • SUM(FieldName) — Sum of a numeric field.
  • AVG(FieldName) — Average of a numeric field.
  • MIN(FieldName) / MAX(FieldName) — Minimum or maximum value.
SOQL — Syntax with GROUP BY and HAVING
SELECT AggregateFunction(FieldName), FieldName2
FROM   ObjectApiName
[WHERE Conditions]
GROUP BY FieldName2
[HAVING AggregateConditions]
Apex — COUNT and AggregateResult
// Simple count
Integer accountCount = [SELECT COUNT() FROM Account];
System.debug('Total Accounts: ' + accountCount);

// Grouped aggregate — returns List<AggregateResult>
List<AggregateResult> results = [
    SELECT Industry, SUM(AnnualRevenue) totalRevenue
    FROM Account
    GROUP BY Industry
];

for (AggregateResult ar : results) {
    System.debug('Industry: ' + ar.get('Industry') + ', Revenue: ' + ar.get('totalRevenue'));
}
SOQL — HAVING Clause Example
SELECT StageName, COUNT(Id)
FROM Opportunity
GROUP BY StageName
HAVING COUNT(Id) > 5

5. SOQL For Loops

SOQL for loops retrieve query results in batches and can reduce heap pressure. Process and release each batch without retaining the full result; retained records and other allocations can still exhaust the heap.

Apex — SOQL For Loop Syntax
for (Account record : [SELECT Id, Name FROM Account]) {
    System.debug(record.Name);
}

Key Advantages

  • Automatic Batching: Salesforce fetches records in batches, reducing the need to hold the full result in memory.
  • Memory Efficiency: Process and release records without retaining the full result. Other allocations and retained records still count toward the heap limit.
  • Still counts as one SOQL query — DML inside the loop is still subject to per-transaction limits, so bulkification remains critical.
Apex — Batch Processing for Mass Updates
public with sharing class LeadProcessor implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([
            SELECT Id, Description FROM Lead WHERE Email != null
            WITH USER_MODE
        ]);
    }

    public void execute(Database.BatchableContext context, List<Lead> scope) {
        for (Lead leadRecord : scope) {
            leadRecord.Description = 'Processed';
        }
        update as user scope;
    }

    public void finish(Database.BatchableContext context) {
    }
}

For large mass updates, use Batch Apex with bounded transactions, as in the example above. Each execute call handles a separate scope and has its own transaction limits. Choose a scope size that also allows for automation invoked by the update.

For Loop vs. Direct List Assignment

  • Use SOQL For Loop: When processing records without retaining the full result; query row and heap limits still apply.
  • Use List<sObject> directly: When expecting a small number of records and needing the full collection in memory for subsequent operations.

6. Introduction to SOSL

SOSL (Salesforce Object Search Language) is designed for text-based searches across multiple sObject types and fields. It's ideal when you need to find records containing specific words or phrases, but don't necessarily know which object or field holds that information.

When to Use SOSL?

  • When you need to search for a phrase across multiple objects simultaneously.
  • When you need to search within a single object, but across multiple fields.
  • When you need fuzzier text matching rather than precise field values.
  • When performing searches similar to the global search bar in the Salesforce UI.

Key Characteristics

  • Searches across multiple objects in a single query.
  • Returns List<List<sObject>> — each inner list contains records of a specific object type.
  • Searches supported indexed fields, which vary by object and search group.
  • Uses a search index for faster results.
  • Some search objects support linguistic features such as lemmatization; behavior varies.

7. SOSL Syntax & Features

SOSL — Basic Syntax
FIND {Search Term}
[IN SearchGroup]
[RETURNING ObjectTypeName [(FieldList)]]
[LIMIT Number]
[OFFSET Number]
  • FIND {Search Term}: The API search term. Wildcards * (zero or more characters) and ? (one character) can appear in the middle or at the end of a term.
  • IN SearchGroup: Fields to search within — ALL FIELDS (default), NAME FIELDS, EMAIL FIELDS, PHONE FIELDS, SIDEBAR FIELDS.
  • RETURNING ObjectTypeName [(FieldList)]: Which sObjects and fields to return. If the field list is omitted, only Id is returned. Multiple objects can be specified. This clause is optional in the API and required in Apex.
  • LIMIT / OFFSET: Set LIMIT globally or within RETURNING; use OFFSET only for a single object, as the final clause.

Examples

SOSL — Search Across Accounts and Contacts
FIND {GenePoint} IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
SOSL — Wildcard Search
FIND {uni*} IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)
SOSL — Phone Field Search
FIND {415\-555\-1212} IN PHONE FIELDS
RETURNING Contact(Id, Name, Phone), Lead(Id, Name, Phone)

Using SOSL in Apex

The standalone examples use API syntax with braces. Apex uses square brackets and a quoted search term, and requires RETURNING, as in [FIND 'term' RETURNING Account(Id)].

Apex — SOSL Query and Result Iteration
List<List<SObject>> searchResults = [
    FIND 'Acme' IN ALL FIELDS
    RETURNING Account(Id, Name), Contact(Id, FirstName, LastName, Email)
];

for (List<SObject> sObjectList : searchResults) {
    if (sObjectList.isEmpty()) continue;

    SObjectType objectType = sObjectList[0].getSObjectType();

    if (objectType == Account.SObjectType) {
        for (Account acc : (List<Account>)sObjectList) {
            System.debug('Found Account: ' + acc.Name + ' (' + acc.Id + ')');
        }
    } else if (objectType == Contact.SObjectType) {
        for (Contact con : (List<Contact>)sObjectList) {
            System.debug('Found Contact: ' + con.FirstName + ' ' + con.LastName);
        }
    }
}

8. Choosing Between SOQL & SOSL

Use SOQL When

  • You know which object(s) you need to query.
  • You need specific fields from a single object or closely related objects.
  • You want to filter on exact field values (e.g., WHERE Status = 'Active').
  • You need aggregate functions (SUM, AVG, COUNT), ordering, or grouping.
  • You need structured filtering or ordering for pagination. Both SOQL and SOSL support OFFSET with limits; choose based on the search and pagination requirements.
SOQL — Targeted Object Query with Relationship
SELECT Id, Name, AnnualRevenue,
       (SELECT Id, FirstName, LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology' AND AnnualRevenue > 500000

Use SOSL When

  • You need to search text across multiple objects simultaneously.
  • You need to search across multiple fields without specifying each one.
  • You don't know which object or field contains the data.
  • You want a Google-like search experience within Salesforce data.
SOSL — Cross-Object Text Search
FIND {"Marketing Campaign"} IN ALL FIELDS
RETURNING Account(Id, Name, Industry), Lead(Id, Name, Status, Company)

SOQL is like a targeted database query — "Give me all Accounts with X criteria and their related Contacts." SOSL is like a search engine — "Find 'X' anywhere it appears across my data."

9. SOQL & SOSL Best Practices

Writing efficient and scalable queries is paramount for avoiding governor limits and ensuring optimal application performance.

General Best Practices

  • Avoid repeated queries inside loops: A query in a loop can quickly exhaust transaction limits. Apex permits 100 synchronous or 200 asynchronous SOQL queries, and 20 SOSL queries per transaction.
  • Bulkify your queries: Collect all IDs first, then perform a single query using IN :collectionVariable.
  • Select only necessary fields: Retrieve only what you need — reduces heap size and improves performance.
  • Use the Query Plan Tool: In Developer Console (Ctrl+I), analyze query performance to see which fields are indexed.
  • Consider Custom Indexes: Mark frequently filtered custom fields as "External ID" or "Unique" to create an index.

SOQL Specific

  • Use selective filters when appropriate: Inspect the query plan; a WHERE clause alone does not guarantee selectivity.
  • Use relationship queries wisely — avoid excessive nesting.
  • Use SOQL for loops to reduce heap pressure when processing query results without retaining the full collection.
Apex — Group Contacts by Account
Set<Id> accountIds = new Set<Id>();
for (Account acc : Trigger.new) {
    accountIds.add(acc.Id);
}

List<Contact> contacts = [
    SELECT Id, Name, AccountId
    FROM Contact
    WHERE AccountId IN :accountIds
];

Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();
for (Contact con : contacts) {
    if (!contactsByAccountId.containsKey(con.AccountId)) {
        contactsByAccountId.put(con.AccountId, new List<Contact>());
    }
    contactsByAccountId.get(con.AccountId).add(con);
}

for (Account acc : Trigger.new) {
    List<Contact> relatedContacts = contactsByAccountId.get(acc.Id);
    if (relatedContacts != null) {
        for (Contact con : relatedContacts) {
            System.debug('Related contact: ' + con.Name);
        }
    }
}

The map preserves all queried contacts for each account. If the application needs a primary contact, define and apply an explicit business rule rather than relying on query order.

How do you enforce data access in queries?

Use user mode when a query must respect the running user's sharing, object permissions, and field-level security. In Apex API version 67.0 and later, database operations default to user mode; earlier versions default to system mode. Specify WITH USER_MODE on a SOQL or SOSL query to make the intended access mode explicit. A sharing declaration alone controls record sharing for system-mode operations and does not enforce object or field permissions. Handle access failures according to the application's requirements, and use system mode only where elevated access is justified. See Salesforce's user-mode guidance.

How do you prevent query injection?

Bind user-supplied values instead of concatenating them into SOQL or SOSL query text. Static Apex queries support bind variables, and dynamic SOQL can use Database.queryWithBinds to supply values separately from the query. Binding values does not validate dynamic object names, field names, or other query structure. Choose those elements from an allowlist of permitted options and enforce the appropriate access permissions. Validate and type-check other inputs according to their context; escaping quotes alone is not a general solution. See Salesforce's injection guidance.

How do you plan queries for large data volumes?

Use selective filters where appropriate and inspect the query plan against representative data. An index can help, but a filter or indexed field alone does not guarantee a selective plan; data distribution and the rest of the query matter. In Apex, ordinary SOQL queries are subject to a 50,000-row transaction limit, and parent-to-child relationship subqueries count separately toward the aggregate-query limit. A SOQL for loop reduces heap pressure but does not remove the row limit. For large mass updates, use Batch Apex and a QueryLocator, with each batch sized for the work and automation it invokes. See the Apex governor limits.

SOSL Specific

  • Be specific in FIND: More precise search terms yield more relevant results.
  • Use IN SearchGroup judiciously: Specify IN NAME FIELDS instead of IN ALL FIELDS when you know where to search.
  • Limit RETURNING objects and fields to only what you genuinely need.
  • Performance consideration: SOSL can be slower than highly selective SOQL on large orgs — use it only when the search paradigm is truly appropriate.

Frequently asked questions

How many records can a SOQL query return?

A single transaction can retrieve 50,000 records across all its SOQL queries. To work with more, use Batch Apex with a QueryLocator, which can return up to 50 million records.

What is a SOQL for loop and why use it?

A SOQL for loop iterates over query results in chunks of 200 records, so large result sets don't fill the heap. It is the safest way to process many records in synchronous Apex.

How do you query parent and child records in SOQL?

Use dot notation for child-to-parent, for example SELECT Name, Account.Name FROM Contact. Use a subquery with the child relationship name for parent-to-child, for example SELECT Name, (SELECT LastName FROM Contacts) FROM Account. Custom relationships end in __r.

How do you prevent SOQL injection?

Use static SOQL with bind variables, or Database.queryWithBinds for dynamic SOQL. If you must build a query string, escape user input with String.escapeSingleQuotes and whitelist field and object names.

What does WITH USER_MODE do in SOQL?

It runs the query with the running user's object permissions, field-level security and sharing rules, and throws an exception if a field isn't accessible. Salesforce recommends it over the older WITH SECURITY_ENFORCED clause.

What is the difference between SOQL and SQL?

SOQL is Salesforce's read-only query language. It looks like SQL SELECT but has no INSERT, UPDATE or DELETE (you use DML for that), no SELECT *, and no arbitrary joins: you follow relationship fields instead, such as Account.Name or a Contacts subquery. Queries are also bound by governor limits.

When should I use SOSL instead of SOQL?

Use SOSL for keyword search across several objects or text fields, such as a global search box. Use SOQL when you know the object and need exact filters, sorting, relationships or aggregates.

Sources: SOQL and SOSL Reference · Execution governors and limits

Get Expert Help

SFX Support — Salesforce + AI solutions. Independent: not affiliated with, endorsed by, or a partner of Salesforce, Inc. Salesforce and Agentforce are trademarks of Salesforce, Inc.