SalesforceWizard

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.

0 of 23 reviewed
On this page (5 sections)SOQL basicsAdvanced queriesQuery securityQuery performanceHow to practise SOQL

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

01

What is SOQL and how is it different from SQL?

Beginner

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 is FIELDS(STANDARD), which works in Apex. FIELDS(ALL) and FIELDS(CUSTOM) work only in the API or tools such as the Salesforce CLI, and need LIMIT 200 or less.
  • There is no JOIN. You reach related records through relationships: Account.Name from 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.

02

How do you write a parent-to-child and a child-to-parent query?

Beginner

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 Contact

Parent 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 Account

Common mistake: Using the object name (Contact) instead of the relationship name (Contacts) in the subquery.

03

What is the difference between a static and a dynamic SOQL query?

Beginner

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.

04

What are aggregate queries?

Beginner

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 StageName

Use HAVING to filter on an aggregate, for example accounts with more than five open cases.

05

How many records can a SOQL query return in Apex?

Beginner

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.

06

What is SOSL and when would you use it instead?

Beginner

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.

07

How do wildcards work with LIKE?

Beginner

% 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.

08

What is the difference between WHERE and HAVING?

Beginner

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) > 5
09

How do you get the total number of records without loading them all?

Beginner

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

10

What is a SOQL for loop and why use it?

Intermediate

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.

11

How do you query deleted or archived records?

Intermediate

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.

12

What are semi-joins and anti-joins?

Intermediate

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.

13

What does FOR UPDATE do in SOQL?

Intermediate

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.

14

How do you query records in the recycle bin?

Intermediate

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.

15

What is OFFSET and what are its limits?

Intermediate

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.

16

How do you query polymorphic fields like WhoId or WhatId?

Advanced

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 Task

Without TYPEOF you can still filter with What.Type = 'Account'.

17

How many relationships can one query include?

Advanced

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

18

How do you prevent SOQL injection?

Intermediate

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.

19

What is the difference between WITH SECURITY_ENFORCED and WITH USER_MODE?

Intermediate

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.

20

What is the risk with dynamic SOQL and how do you avoid it?

Intermediate

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

21

What makes a SOQL query selective?

Advanced

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.

22

What does the Query Plan tool tell you?

Advanced

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.

23

A query that was fast last year now times out. How do you investigate?

Advanced

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.

Chat on WhatsApp