How Salesforce Executes a SOQL Query
By the end of this lesson, you'll be able to:
- Name the major stages Salesforce goes through when running a SOQL query
- Explain where the query optimizer and indexes fit into that sequence
- Connect this sequence back to the selectivity concept from the previous lesson
Prerequisites: "Query Selectivity and Performance"
The simplified sequence
When a SOQL query runs, Salesforce roughly works through:
- Parsing — the query text is checked for valid syntax.
- Permission and sharing checks — which records the running user is even allowed to see (covered in depth in a later Security module).
- Query optimization — the platform's optimizer decides the fastest way to actually retrieve matching rows, favoring indexed fields when the
WHEREclause allows it. - Execution — the underlying database retrieves the matching rows.
- Returning results — rows are converted into
sObjectrecords and handed back to Apex as aList.
Where selectivity fits in
Step 3 is exactly where the previous lesson's "selectivity" concept becomes concrete: the optimizer can only take the fast, indexed path when the query's WHERE clause actually allows it. A non-selective query forces the optimizer into a slower, broader scan — the direct cause of the timeout risk discussed previously.
Why sharing rules matter, previewed
List<Account> accounts = [SELECT Id, Name FROM Account]; // respects sharing by default
Step 2 means a plain SOQL query, by default, only returns records the currently running user actually has permission to see — two different users running the exact same query line can get different results. This default behavior (and how to deliberately override it) is covered fully in the upcoming Security module — this lesson's job is just to place it correctly in the overall sequence.
Exercise
As a comment, explain why two different users running the exact identical SOQL query could get different numbers of results back.
Show hint
Think about step 2 in the sequence.
How Salesforce Executes a SOQL Query Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
This closing lesson walks through what actually happens between writing [SELECT ...] and getting a List<sObject> back — tying together selectivity, indexes, and sharing rules into one coherent picture.