SOQL and SOSL tutorial with examples
On this page (9 sections)
Lesson 1: SOQL basicsLesson 2: Relationship queriesLesson 3: Aggregate queriesLesson 4: SOSL: searching across objectsLesson 5: Writing fast, safe queriesWhat changed in 2025–26How this is asked in interviewsPractise this topicCommon questionsSOQL (Salesforce Object Query Language) reads records from Salesforce, and SOSL (Salesforce Object Search Language) searches text across many objects. Both are used in Apex, LWC, integrations and tools such as the Developer Console.
In this topic: Lesson 1: SOQL basics · Lesson 2: Relationship queries · Lesson 3: Aggregate queries · Lesson 4: SOSL: searching across objects · Lesson 5: Writing fast, safe queries
Lesson 1: SOQL basics
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
WHERE Industry = 'Banking' AND AnnualRevenue > 1000000
ORDER BY AnnualRevenue DESC
LIMIT 10SELECTlists fields (there is noSELECT *; useFIELDS(STANDARD)in some tools).WHEREfilters with operators such as=,!=,<,LIKE 'Acme%',INandINCLUDES(multi-select picklists).- Date literals make filters easy:
CreatedDate = LAST_N_DAYS:30,CloseDate = THIS_QUARTER. ORDER BY,LIMITandOFFSETsort and page results.
Lesson 2: Relationship queries
Child to parent: use dot notation on the relationship name.
SELECT Name, Account.Name, Account.Owner.Name FROM ContactParent to child: use a subquery with the child relationship name (usually plural, and __r for custom relationships).
SELECT Name, (SELECT LastName, Email FROM Contacts) FROM Account
SELECT Name, (SELECT Amount__c FROM Invoices__r) FROM AccountLesson 3: Aggregate queries
SELECT StageName, COUNT(Id) total, SUM(Amount) value
FROM Opportunity
WHERE IsClosed = false
GROUP BY StageName
HAVING SUM(Amount) > 100000Functions include COUNT(), SUM(), AVG(), MIN() and MAX(). In Apex, results come back as AggregateResult objects, read with ar.get('total').
Lesson 4: SOSL: searching across objects
FIND 'acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name, Email), Lead(Id, Company)| SOQL | SOSL | |
|---|---|---|
| Purpose | Read records from one object (and related ones) | Search text across many objects at once |
| Use when | You know which object and which fields to filter | You want to find a word wherever it appears |
| Returns | A list of records | A list of lists, one per object |
| Limit per transaction (Apex) | 100 queries (sync) | 20 searches |
Lesson 5: Writing fast, safe queries
- Filter on indexed fields (Id, Name, external IDs, lookup fields, CreatedDate) on large objects so queries are selective.
- Never query inside a loop in Apex: query once and use a map.
- Use bind variables (
WHERE Id IN :accountIds) instead of building query strings, to avoid SOQL injection. - Add
WITH USER_MODEso the query respects the user's object and field permissions and sharing. - Try queries first in the Developer Console Query Editor or the VS Code SOQL Builder.
What changed in 2025–26
WITH USER_MODEapplies the user's object, field and record access to a query. It replacesWITH SECURITY_ENFORCED.Database.queryWithBindslets dynamic queries use bind variables safely.- Apex cursors help process very large result sets in steps.
- Multi-level parent-to-child subqueries are now supported in newer API versions, but keep queries simple: deep nesting is hard to read and slow.
How this is asked in interviews
- "SOQL or SOSL?" SOQL when you know the object and filters; SOSL for free-text search across objects.
- "Your query times out on a big object. What do you do?" Make it selective: filter on indexed fields, check the Query Plan tool.
- "How do you stop SOQL injection?" Bind variables, queryWithBinds, allow-listed field names, user mode.
- "Write a query for accounts with their contacts." Practise relationship queries until you can write them without thinking. See SOQL questions.
How to answer: Start with what you would do, say why, mention the limit or risk you are avoiding, and finish with a real example from a project or practice org. One clear minute beats five minutes of definitions.
Practise this topic
- Apex practice exercises, with model answers
- SOQL interview questions
- Governor limits scenarios
- Developer mock interview
Common questions
01What is the difference between SOQL and SQL?
What is the difference between SOQL and SQL?
What the interviewer is checking: Whether you understand how Salesforce data is organised: objects and relationships, read-only queries and governor limits.
SOQL looks like SQL's SELECT, but it works differently in a few ways that interviewers like to check:
- It only reads data. To insert, update or delete records you use DML in Apex (or the API), not SOQL.
- It queries Salesforce objects and fields, not database tables, and you normally name each field you want. There is no
SELECT *. The closest thing isFIELDS(STANDARD), which works in Apex.FIELDS(ALL)andFIELDS(CUSTOM)work only in the API or tools such as the Salesforce CLI, and needLIMIT 200or less. - There is no JOIN. You reach related records through relationships:
Account.Namefrom a contact (child to parent), or a subquery such as(SELECT LastName FROM Contacts)(parent to child). You cannot join two objects that have no relationship. - Governor limits apply: in one Apex transaction you can run 100 queries (200 in async Apex) and fetch up to 50,000 rows in total.
A good one-line summary for the interview: "SOQL is a read-only query language for Salesforce objects, built around relationships and limits, not tables and joins."
Common mistake: Saying SOQL supports JOIN or SELECT *, or that you can update records with it.
02How many records can a SOQL query return in Apex?
How many records can a SOQL query return in Apex?
Up to 50,000 rows per transaction in total. For more, use Batch Apex or Apex cursors.
03What is a selective query?
What is a selective query?
A query whose filter uses an index and returns a small enough share of the records that the database doesn't scan the whole table. It matters on objects with hundreds of thousands of records or more.