SOQL interview questions and answers
From your first relationship query to the selectivity questions senior interviews love. Each answer includes a query you can run in your own org.
On this page (5 sections)
SOQL basicsAdvanced queriesQuery securityQuery performanceHow to practise SOQLNew to this topic? Learn SOQL and SOSL step by step before you practise.
SOQL questions show up in admin, developer and even consultant interviews, because almost everything in Salesforce starts with getting the right records. The questions below go from the basics to the performance topics that senior interviews focus on.
Questions in each topic go from beginner to advanced. Use On this page to jump to the topic you need.
SOQL basics
01What is SOQL and how is it different from SQL?
What is SOQL and how is it different from SQL?
What the interviewer is checking: Whether you know SOQL is read-only, works on objects and relationships rather than tables and joins, and is limited by governor limits.
SOQL (Salesforce Object Query Language) reads records from Salesforce objects.
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 do you write a parent-to-child and a child-to-parent query?
How do you write a parent-to-child and a child-to-parent query?
What the interviewer is checking: Whether you can get related data in one query, which is the basis of bulk-safe code.
Child to parent uses dot notation on the lookup field:
SELECT Name, Account.Name, Account.Industry FROM ContactParent to child uses a subquery with the child relationship name, which is plural for standard objects and ends in __r for custom ones:
SELECT Name, (SELECT LastName FROM Contacts) FROM AccountCommon mistake: Using the object name (Contact) instead of the relationship name (Contacts) in the subquery.
03What is the difference between a static and a dynamic SOQL query?
What is the difference between a static and a dynamic SOQL query?
Static SOQL is written inline in square brackets and checked when the code is saved. Dynamic SOQL is built as a string at runtime and run with Database.query(), which is useful when the fields or filters depend on user input.
Dynamic SOQL is more flexible but you lose compile-time checking and must protect it against SOQL injection.
04What are aggregate queries?
What are aggregate queries?
Aggregate functions such as COUNT, SUM, AVG, MIN and MAX summarise records, usually with GROUP BY. In Apex they return AggregateResult objects.
SELECT StageName, COUNT(Id) total, SUM(Amount) value
FROM Opportunity
GROUP BY StageNameUse HAVING to filter on an aggregate, for example accounts with more than five open cases.
05How many records can a SOQL query return in Apex?
How many records can a SOQL query return in Apex?
In a single transaction, all SOQL queries together can retrieve at most 50,000 rows. Batch Apex's start method with a QueryLocator can handle up to 50 million.
For large result sets inside normal Apex, use a SOQL for loop, which fetches records in chunks of 200 and keeps heap usage low.
06What is SOSL and when would you use it instead?
What is SOSL and when would you use it instead?
SOSL searches text across several objects in one call:
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Name), Contact(FirstName, LastName)Use it for search boxes and global search features. Use SOQL when you know the object and want precise filters.
07How do wildcards work with LIKE?
How do wildcards work with LIKE?
% matches any number of characters and _ matches exactly one. WHERE Name LIKE 'Acme%' finds names starting with Acme. LIKE is not case-sensitive. A leading wildcard such as '%acme' cannot use an index, so it is slow on large objects.
08What is the difference between WHERE and HAVING?
What is the difference between WHERE and HAVING?
WHERE filters records before grouping: HAVING filters groups after aggregation.
SELECT AccountId, COUNT(Id) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING COUNT(Id) > 509How do you get the total number of records without loading them all?
How do you get the total number of records without loading them all?
Use SELECT COUNT() FROM Contact WHERE ..., which returns an Integer in Apex. COUNT() still counts towards the rows-returned governor limit for every record it counts, so on very large objects use filters or a batch job.
Advanced queries
10What is a SOQL for loop and why use it?
What is a SOQL for loop and why use it?
A SOQL for loop iterates over query results without loading them all into memory at once:
for (List<Account> chunk : [SELECT Id, Name FROM Account WHERE Industry = 'Banking']) {
// process up to 200 records at a time
}It helps you stay under the heap size limit when processing thousands of records.
11How do you query deleted or archived records?
How do you query deleted or archived records?
Add ALL ROWS in Apex to include records in the Recycle Bin and archived activities, and filter on IsDeleted = true if you only want deleted ones.
12What are semi-joins and anti-joins?
What are semi-joins and anti-joins?
They are subqueries in a WHERE clause using IN or NOT IN:
-- Accounts that have at least one open case
SELECT Id, Name FROM Account
WHERE Id IN (SELECT AccountId FROM Case WHERE IsClosed = false)Using NOT IN gives you the opposite, for example accounts with no opportunities.
13What does FOR UPDATE do in SOQL?
What does FOR UPDATE do in SOQL?
It locks the returned records until the transaction ends, so another transaction cannot change them at the same time. Use it when two processes might update the same record, for example assigning the next number from a counter record. Other transactions trying to lock the same records wait and can fail with a lock error, so keep such transactions short.
14How do you query records in the recycle bin?
How do you query records in the recycle bin?
Add ALL ROWS in Apex to include deleted and archived records, and filter on IsDeleted = true to get only deleted ones. In the REST API, use the queryAll endpoint instead.
15What is OFFSET and what are its limits?
What is OFFSET and what are its limits?
OFFSET skips a number of rows, for simple paging: LIMIT 50 OFFSET 100. The maximum offset is 2,000 rows, so it is not suitable for paging through large data. Use a filter on the last ID or date you saw (keyset paging), or a query locator, instead.
16How do you query polymorphic fields like WhoId or WhatId?
How do you query polymorphic fields like WhoId or WhatId?
Polymorphic lookups can point to different object types. Use TYPEOF to pick fields depending on the type:
SELECT Subject,
TYPEOF What
WHEN Account THEN Name, Industry
WHEN Opportunity THEN Name, StageName
END
FROM TaskWithout TYPEOF you can still filter with What.Type = 'Account'.
17How many relationships can one query include?
How many relationships can one query include?
A query can include up to 55 child-to-parent relationships (such as Account.Owner.Name) and up to 20 parent-to-child subqueries. Each child-to-parent path can go up to five levels deep. In practice, a query near these limits is a sign it should be split or the data model reviewed.
Query security
18How do you prevent SOQL injection?
How do you prevent SOQL injection?
Use bind variables, even in dynamic SOQL. Database.queryWithBinds() lets you pass a map of bind values so user input is never concatenated into the query string.
If you must concatenate, escape the input with String.escapeSingleQuotes() and whitelist any field or object names against the schema.
19What is the difference between WITH SECURITY_ENFORCED and WITH USER_MODE?
What is the difference between WITH SECURITY_ENFORCED and WITH USER_MODE?
Both make a query respect the running user's object and field permissions. WITH SECURITY_ENFORCED throws an exception if any field is not accessible and does not check fields in the WHERE clause.
WITH USER_MODE is the newer, recommended option: it enforces sharing as well as object and field permissions, checks the whole query, and can report all inaccessible fields. New code should use user mode.
20What is the risk with dynamic SOQL and how do you avoid it?
What is the risk with dynamic SOQL and how do you avoid it?
Dynamic SOQL builds the query as a string at run time, so user input concatenated into it can change the query. This is SOQL injection. Use bind variables, which Database.queryWithBinds supports with a map of values, or escape input with String.escapeSingleQuotes. For field and object names, check them against a list of allowed values or the schema describe results.
Query performance
21What makes a SOQL query selective?
What makes a SOQL query selective?
A query is selective when its filter uses an indexed field and the filter matches a small enough share of the records, so the optimizer can use the index instead of scanning the table.
Standard indexed fields include Id, Name, OwnerId, CreatedDate, SystemModstamp, lookup and master-detail fields, and external ID and unique fields. Filters like !=, NOT LIKE, leading wildcards (LIKE '%abc') and comparisons with null usually stop an index being used.
22What does the Query Plan tool tell you?
What does the Query Plan tool tell you?
The Query Plan tool in the Developer Console shows how Salesforce would run a query: which index it would use, the estimated cardinality and a relative cost. A cost under 1 means the query is selective.
It is the quickest way to prove whether a slow query needs a different filter or a custom index.
23A query that was fast last year now times out. How do you investigate?
A query that was fast last year now times out. How do you investigate?
Data volume has probably crossed a point where the filter is no longer selective. Run the query in the Query Plan tool, check whether the filter fields are indexed and how many records match each filter, and look for new filters that disable indexes.
Fixes include adding a selective filter such as a date range, using an external ID or custom index, archiving old data, or moving the processing to Batch Apex.
How to practise SOQL
Open the Developer Console or VS Code in a free Developer Edition org and write each query above yourself. Then read the related governor limits scenarios, because most SOQL interview follow-ups are about limits.