CRM NEWS TODAY

Launch. Integrate. Migrate.
Or anything CRM.

104+ CRM Platforms
Covered

Get Complete CRM Solution

Salesforce SOQL: What It Is and How to Write Queries (2026)

Salesforce SOQL guide for 2026: SELECT syntax, WHERE operators, date literals, relationship queries, aggregate functions, and performance best practices for admins and developers.

SOQL — Salesforce Object Query Language — is the query language for retrieving data from Salesforce. It resembles SQL’s SELECT syntax but operates within Salesforce’s object model constraints: no multi-table JOINs, no INSERT or UPDATE commands, and a set of relationship-traversal patterns that replace SQL’s JOIN mechanism. Any Salesforce administrator using Data Loader, developer writing Apex code, or integration engineer querying the REST API needs to understand SOQL to retrieve data efficiently. This guide covers SOQL from the basic SELECT syntax through relationship queries, aggregate functions, date literals, and performance best practices.

The best guide is the one that makes querying feel understandable.

A useful explanation should help the reader see where SOQL fits into Salesforce work.

That means the guide should focus on practical querying rather than syntax alone.

For many users, the value is in being able to ask the database for exactly what they need.

It should also show how queries support reporting, debugging, and data analysis.

A good guide should explain what SOQL is used for and why it matters when working with CRM data.

That makes it one of the most important query tools in the platform.

Salesforce SOQL is useful because it gives users and developers a way to query data inside Salesforce in a structured, precise way. It helps teams pull the records they need without relying on broad or manual searches.

SOQL Basics: SELECT, FROM, WHERE

The minimum viable SOQL query follows this structure:

SELECT Field1, Field2, Field3 FROM ObjectName WHERE FilterField = 'FilterValue'

A concrete example — retrieve all Opportunities closing this month with a value over $50,000:

SELECT Id, Name, Amount, StageName, CloseDate, Account.Name
FROM Opportunity
WHERE CloseDate = THIS_MONTH
AND Amount > 50000
ORDER BY CloseDate ASC
LIMIT 200

Key syntax rules:

  • Object API names are case-insensitive in SOQL but conventionally written in PascalCase (Opportunity, Contact, Account, CustomObject__c)
  • Custom objects have an __c suffix (MyCustomObject__c); custom fields also have __c (Custom_Field__c)
  • String values in WHERE clauses are enclosed in single quotes
  • Number and boolean values are not quoted (Amount > 50000, IsActive = true)
  • SOQL does not support SELECT * — you must specify each field explicitly. Use Schema Builder or Object Manager to look up available field API names.
  • LIMIT is optional but recommended — queries without LIMIT can return up to 50,000 rows

WHERE Clause Operators

SOQL supports these comparison operators:

  • = and !=: equality and inequality — StageName = 'Prospecting', IsWon != true
  • <, >, <=, >=: numeric and date comparisons — Amount >= 100000
  • LIKE: pattern matching with % wildcard — Name LIKE 'Acme%' matches any Name starting with “Acme”. LIKE is case-insensitive. % matches any sequence of characters; _ matches any single character.
  • IN and NOT IN: match against a list of values — StageName IN ('Proposal/Price Quote', 'Negotiation/Review')
  • INCLUDES and EXCLUDES: for multi-select picklist fields — Product_Category__c INCLUDES ('Software', 'SaaS') matches records where the multi-select picklist includes any of the specified values
  • AND, OR, NOT: logical operators for combining conditions. Use parentheses to control precedence: WHERE (StageName = 'Prospecting' OR StageName = 'Qualification') AND Amount > 10000

Date Literals

SOQL’s date literals are one of its most useful features — they allow time-relative filtering without hardcoding date values that expire:

  • TODAY: the current day (midnight to midnight in the user’s timezone)
  • YESTERDAY: the previous day
  • THIS_WEEK: current calendar week (Sunday through Saturday)
  • LAST_WEEK: the previous week
  • THIS_MONTH: current calendar month
  • LAST_MONTH: previous calendar month
  • THIS_QUARTER: current fiscal quarter (based on org’s fiscal year setting)
  • THIS_YEAR: current calendar year
  • LAST_N_DAYS:n: rolling window of n days — LAST_N_DAYS:30 = last 30 days. Available variants: LAST_N_WEEKS, LAST_N_MONTHS, LAST_N_QUARTERS, LAST_N_YEARS
  • NEXT_N_DAYS:n: next n days from today

Example: contacts with no activity in the last 90 days:

SELECT Id, Name, Email, LastActivityDate
FROM Contact
WHERE LastActivityDate < LAST_N_DAYS:90
AND IsDeleted = false
ORDER BY LastActivityDate ASC NULLS FIRST

NULLS FIRST places records where LastActivityDate is null (no activity ever logged) at the top of results — useful for identifying completely untouched contacts.

Relationship Queries: Traversing Object Relationships

SOQL does not support SQL-style JOINs. Instead, it uses relationship names to traverse the connections between related objects. Two traversal directions exist:

Child-to-Parent (Forward Traversal)

Access parent record fields from a child query using the relationship name followed by a period. A Contact’s parent Account is traversed as Account.Name:

SELECT Id, FirstName, LastName, Email, Account.Name, Account.Industry
FROM Contact
WHERE Account.Industry = 'Technology'

This returns Contact records with their parent Account’s Name and Industry fields — equivalent to an INNER JOIN in SQL. The relationship name is the field’s relationship label, not the lookup field API name (for standard objects, the relationship name is typically the object name; for custom lookup fields, it is the field API name without __c, plus __r).

Custom lookup field example: if a Contact has a custom lookup field to a Region object called Primary_Region__c, the relationship traversal is:

SELECT Id, Name, Primary_Region__r.Name FROM Contact

Parent-to-Child (Subquery)

Retrieve child records as a nested result within a parent query using a subquery in parentheses. The child relationship name is the plural form of the child object’s relationship label:

SELECT Id, Name,
  (SELECT Id, FirstName, LastName, Email FROM Contacts),
  (SELECT Id, Name, StageName, Amount FROM Opportunities WHERE IsClosed = false)
FROM Account
WHERE Name LIKE 'Acme%'

This returns Account records with their associated Contacts and open Opportunities as nested lists. Subqueries in SOQL are limited to one level deep — you cannot have a subquery inside a subquery. A maximum of 20 child relationship subqueries are allowed per SOQL statement.

Aggregate Functions

SOQL supports aggregate functions for summary data:

SELECT StageName, COUNT(Id) RecordCount, SUM(Amount) TotalAmount, AVG(Amount) AvgAmount
FROM Opportunity
WHERE IsClosed = false
AND CloseDate = THIS_QUARTER
GROUP BY StageName
ORDER BY TotalAmount DESC

Aggregate functions: COUNT(field), COUNT_DISTINCT(field), SUM(field), AVG(field), MIN(field), MAX(field).

When using aggregate functions, all non-aggregate fields in SELECT must appear in GROUP BY. The HAVING clause filters on aggregate results (equivalent to SQL HAVING):

SELECT AccountId, COUNT(Id) OpportunityCount
FROM Opportunity
WHERE IsWon = true
GROUP BY AccountId
HAVING COUNT(Id) > 5

This returns Accounts with more than 5 won Opportunities.

ORDER BY, LIMIT, and OFFSET

  • ORDER BY: ORDER BY Amount DESC (descending), ORDER BY CloseDate ASC (ascending — default). Multiple fields: ORDER BY StageName ASC, Amount DESC
  • LIMIT: LIMIT 100 — restrict results to n rows. Maximum 2,000 rows per query in some contexts.
  • OFFSET: OFFSET 200 — skip the first n rows before returning results. Used with LIMIT for pagination: query 1 is LIMIT 200 OFFSET 0, query 2 is LIMIT 200 OFFSET 200. OFFSET maximum is 2,000.

Where to Write and Test SOQL Queries

  • Developer Console: In Salesforce, click the gear icon → Developer Console → Query Editor tab. Write and execute SOQL queries against your org’s live data. Results appear in a grid. Free, built-in.
  • Workbench: A free, browser-based Salesforce admin tool at workbench.developerforce.com. Provides a SOQL query builder with field selection via dropdown and a results grid. Useful for admins who prefer a GUI over writing raw SOQL.
  • Salesforce REST API query endpoint: GET /services/data/vXX.X/query?q=SELECT+Id+FROM+Contact+LIMIT+5 — URL-encode the query string.
  • Data Loader: Use SOQL in the Extract tab — paste your SOQL query to export matching records to a CSV file.
  • VS Code Salesforce Extension Pack: includes a SOQL editor with autocomplete for field names and object API names.

SOQL Performance Best Practices

Use indexed fields in WHERE clauses: Salesforce maintains indexes on standard fields (Id, Name, CreatedDate, SystemModstamp, LastModifiedDate, OwnerId, and email/phone fields on some objects) and custom fields marked as External ID or Unique. Filtering on indexed fields uses index scans rather than full table scans — dramatically faster for large datasets.

Avoid non-selective queries: if a WHERE clause returns more than 1 million records in a large org, Salesforce throws a “non-selective query” error because the query is scanning too much data. Narrow the query with additional filters on indexed fields — typically adding a date range filter (CreatedDate = LAST_N_DAYS:90) is the fastest fix.

Avoid querying more fields than needed: each additional field in SELECT adds to the query’s data transfer volume. In Apex, over-fetching fields increases heap usage toward the 6MB Apex heap limit.

Use LIMIT: always add LIMIT to exploratory queries — without it, a query against a large dataset returns all matching records and can time out or consume API call limits.

SOQL vs SOSL

SOSL (Salesforce Object Search Language) is often confused with SOQL. The distinction:

  • SOQL: structured queries on a specific object — “give me all Contacts where Account.Name = ‘Acme’ and Email is not blank”
  • SOSL: full-text search across multiple objects simultaneously — “search all objects for the text ‘Smith’ and return matching Contact, Lead, and Account records”

SOSL is used when you need to find a record but don’t know which object it’s on, or when you need to match partial text strings across fields. SOQL is used for all structured data retrieval with known object and field context.

The best query setup is the one that returns the right records clearly. If the request is badly written, the result is harder to trust.

Conclusion

SOQL is a learned skill that pays compounding dividends across Salesforce administration, integration development, and data analysis. The basics — SELECT, FROM, WHERE, relationship traversal — cover the majority of daily use cases. Aggregate functions and date literals unlock reporting-grade data retrieval directly from the query layer. Performance optimisation (indexed fields, selective WHERE clauses, appropriate LIMIT usage) becomes important at scale, particularly in Apex triggers and batch jobs where governor limits constrain query behaviour. Start practising in the Developer Console against your own org’s data — the fastest way to internalise SOQL syntax is to write real queries against real data.


Sources
Salesforce, SOQL and SOSL Reference (2026)
Salesforce, Query and Search in Apex Documentation (2026)
Salesforce, Performance Tuning for SOQL Queries (2026)
Salesforce Trailhead, Apex Basics and Database Module (2026)

We Set Up, Integrate & Migrate Your CRM

Whether you're launching Salesforce from scratch, migrating to HubSpot, or connecting Zoho with your existing tools — we handle the complete implementation so you don't have to.

  • Salesforce initial setup, configuration & go-live
  • HubSpot implementation, data import & onboarding
  • Zoho, Dynamics 365 & Pipedrive deployment
  • CRM-to-CRM migration with full data transfer
  • Third-party integrations (ERP, email, payments, APIs)
  • Post-launch training, support & optimization

Tell us about your project

No spam. Your details are shared only with a vetted consultant.

Get An Expert