October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Salesforce SOQL Optimization: Practical Practices for Better Apex

Improve Apex query design by retrieving only necessary data, using selective filters, respecting relationship limits, and matching query strategy to workload.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To optimize SOQL in Apex, retrieve only the fields and records the code needs, use filters that are selective for your org’s data, and design relationship traversals and bulk workloads within Salesforce’s limits. An index alone does not guarantee a fast query: a nonselective filter can prevent indexed columns from being used. Salesforce’s large-data-volume guidance recommends tuning against the actual workload rather than relying on a universal query pattern.

How do I optimize SOQL queries in Apex?

Start with the records the code must act on, then shape the query to return as little data as practical. Salesforce’s large-data-volume guidance recommends focused queries, reducing query scope, and using selective filters. These practices can reduce unnecessary work, but the actual query plan depends on the org’s data distribution and query shape.

Retrieve only the required fields

Select explicit fields needed by the code rather than retrieving more data than the operation uses. In Apex, FIELDS(STANDARD) is supported, but unbounded FIELDS(ALL) and FIELDS(CUSTOM) are not supported in inline or dynamic SOQL. Explicit selection also helps keep statements within SOQL character limits and REST requests within URI length limits, as described in Salesforce’s SELECT reference.

Make filters selective for your data

A useful filter reduces the candidate records the optimizer must consider. Indexed fields can help, as can fields with a wider range of possible values, but indexing by itself is not a performance guarantee: Salesforce notes that nonselective filters may prevent indexed columns from being used. Check the query’s behavior against representative data before claiming an improvement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Avoid patterns Salesforce flags as problematic

  • Avoid negative conditions such as Status__c != 'Failed' or Status__c != NULL where a selective positive condition can express the requirement.
  • Prefer Id IN :ids to a long chain of OR conditions when matching a set of known IDs.
  • Avoid filtering on cross-object reference formula fields; Salesforce identifies them as non-indexable. Formula fields are computed at query time, and dynamic, non-deterministic references can make formula filters especially unsuitable.
  • For first- and last-name searches, Salesforce’s guidance recommends using the Name field rather than filtering each name component separately.
  • Choose SOQL for structured record retrieval and SOSL when the task is text search; the query language should match the search problem.

What are the best practices for SOQL relationship queries?

SOQL traverses relationships defined in Salesforce; it does not provide arbitrary SQL-style joins. Use dot notation to travel from a child record to its parent, and a parent-to-child subquery to retrieve related children. Salesforce’s relationship-query documentation describes these query shapes.

Check relationship limits before nesting

Salesforce’s SOQL/SOSL limits reference states that a query can include up to 55 child-to-parent relationships and 20 parent-to-child relationships; custom objects allow up to 40 child-to-parent relationships. A child-to-parent relationship path can traverse up to five levels.

Parent-to-child nesting depends on API version and context. API version 57.0 and earlier supports two levels; version 58.0 and later supports up to five levels for standard and custom objects through REST, SOAP, and Apex query calls. The five-level support does not apply to big objects, external objects, or Bulk API and Bulk API 2.0. Confirm the target API version and object type before building a query around deeper nesting.

When to retrieve related records separately

A relationship subquery is useful when related records are needed as part of the same operation and the supported query shape is manageable. If the query becomes too broad, exceeds relationship constraints, or makes it difficult to control the amount of data retrieved, consider a narrower query or separate retrieval and processing. The right choice depends on the required records and workload; relationship depth alone does not determine which approach performs better.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should SOQL change for large data volumes?

Large data volumes are a workload-design issue, not a reason to assume one query pattern will work everywhere. For timeout risk, Salesforce recommends tuning the query, reducing its scope, and using selective filters. For bulk work, its guidance also identifies Bulk API 2.0 Query and batch Apex as possible approaches.

Choose an approach based on the workload

  • Interactive or transactional work: Keep the query tightly scoped and retrieve only what the current operation needs.
  • Large extraction: Consider Bulk API 2.0 Query when the task is a bulk data operation rather than an interactive Apex transaction.
  • Batch Apex: If timeouts persist, Salesforce’s guidance mentions using a LIMIT clause, starting at 100,000 records, and chaining sets or moving filter logic into execute. These are workload options, not guarantees that a job will avoid timeouts; test with representative data.

Measure the actual query behavior

Data distribution matters. A filter that is selective in a small development org may not be selective in production. Use appropriate Salesforce diagnostics and representative data to inspect query behavior before deciding that a rewrite improved performance. Do not infer speed solely from the presence of an index or from a query’s appearance.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which SOQL limits matter in Apex?

Salesforce’s SOQL/SOSL limits reference distinguishes statement and API query limits from Apex execution limits. Keep those contexts separate when designing a query:

Limit Salesforce documentation context
100,000 characters Default maximum SOQL statement length.
2,000 rows per API request Generally applies to API query results for API version 28.0 and later unless custom query limits are specified. The reference notes that Apex has additional limits; this is not the per-transaction Apex query-row limit.
2,000 rows Maximum value for SOQL OFFSET.

These figures come from Salesforce’s limits reference. It does not provide a complete Apex governor-limit table, so verify the current Apex-specific limits in Salesforce’s Apex Governor Limits documentation for the execution context you are using.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.