During a performance review you discover that a reporting query contains this pattern:
SELECT ...
FROM (
SELECT CustomerID, SUM(TotalDue) AS TotalSpent
FROM dbo.Orders
WHERE OrderDate >= '2024-01-01'
GROUP BY CustomerID
) AS recent_orders
JOIN dbo.Orders o1 ON o1.CustomerID = recent_orders.CustomerID
JOIN dbo.Orders o2 ON o2.CustomerID = recent_orders.CustomerID;
The execution plan shows the derived subquery against the 50-million-row Orders table is executed three times, causing very high logical reads. Without changing the final results, which action is most likely to reduce execution time and I/O?
Insert the subquery results into a local temporary table (#recent_orders), add an index on CustomerID, and join the main query to that temporary table.
Rewrite the derived subquery as a common table expression (CTE) so SQL Server can cache the result internally.
Add an OPTION (FORCESEEK) hint to every Orders reference to force index seeks during each scan.
Add WITH (NOLOCK) hints to all Orders references to avoid locking during the scans.
Persisting the subquery result in a session-scoped temporary table means the expensive aggregation runs only once. The main query can then join to the smaller, indexed #recent_orders table, eliminating two extra scans of the 50-million-row Orders table and sharply reducing logical reads. A CTE is usually inlined, so the optimizer may still re-evaluate it; index or lock hints leave the multiple scans in place and merely influence access or concurrency methods, so they do not address the root cause.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What is a session-scoped temporary table in SQL?
Open an interactive chat with Bash
Why is indexing a temporary table like #recent_orders important?
Open an interactive chat with Bash
Why is a common table expression (CTE) not ideal in this scenario?
Open an interactive chat with Bash
CompTIA Data+ DA0-002 (V2)
Data Acquisition and Preparation
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
Pass with Confidence.
IT & Cybersecurity Package
You have hit the limits of our free tier, become a Premium Member today for unlimited access.
Military, Healthcare worker, Gov. employee or Teacher? See if you qualify for a Community Discount.
Monthly
$19.99 $11.99
$11.99/mo
Billed monthly, Cancel any time.
$19.99 after promotion ends
3 Month Pass
$44.99 $26.99
$8.99/mo
One time purchase of $26.99, Does not auto-renew.
$44.99 after promotion ends
Save $18!
MOST POPULAR
Annual Pass
$119.99 $71.99
$5.99/mo
One time purchase of $71.99, Does not auto-renew.
$119.99 after promotion ends
Save $48!
BEST DEAL
Lifetime Pass
$189.99 $113.99
One time purchase, Good for life.
Save $76!
What You Get
All IT & Cybersecurity Package plans include the following perks and exams .