SalesforceWizard

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 questions

SOQL (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 10
  • SELECT lists fields (there is no SELECT *; use FIELDS(STANDARD) in some tools).
  • WHERE filters with operators such as =, !=, <, LIKE 'Acme%', IN and INCLUDES (multi-select picklists).
  • Date literals make filters easy: CreatedDate = LAST_N_DAYS:30, CloseDate = THIS_QUARTER.
  • ORDER BY, LIMIT and OFFSET sort 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 Contact

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

Lesson 3: Aggregate queries

SELECT StageName, COUNT(Id) total, SUM(Amount) value
FROM Opportunity
WHERE IsClosed = false
GROUP BY StageName
HAVING SUM(Amount) > 100000

Functions 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)
SOQLSOSL
PurposeRead records from one object (and related ones)Search text across many objects at once
Use whenYou know which object and which fields to filterYou want to find a word wherever it appears
ReturnsA list of recordsA 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_MODE so 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_MODE applies the user's object, field and record access to a query. It replaces WITH SECURITY_ENFORCED.
  • Database.queryWithBinds lets 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

Common questions

01

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

03

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.

Chat on WhatsApp