patternsqlMinor
If a query contains two identical subqueries, will they both run?
Viewed 0 times
queryidenticalbothtwowillcontainstheysubqueriesrun
Problem
Say I have a
Will the
SELECT query that contains two identical subqueries, like the below:SELECT
(SELECT SUM(Price)
FROM Product p
WHERE p.GroupID = g.GroupID) AS 'TotalCost',
(SELECT SUM(Price)
FROM Product p
WHERE p.GroupID = g.GroupID) * 0.1 AS 'GST'
FROM Group gWill the
SUM subquery be performed twice, or will SQL use the first result for the second field?Solution
Identical subqueries are normally only performed once. However, the way you write a query isn't neccessarily the actual execution order, so there are no guarantees.
To make sure, view your estimated execution plan with one or both of the subqueries, and compare them.
In your example, you could place the subquery in a JOIN instead, which would make it both reusable and more easy to read.
To make sure, view your estimated execution plan with one or both of the subqueries, and compare them.
In your example, you could place the subquery in a JOIN instead, which would make it both reusable and more easy to read.
SELECT g.*, p.Amt AS 'TotalCost', p.Amt * 0.1 AS 'GST'
FROM Group g
LEFT JOIN (SELECT GroupID, SUM(Price) AS Amt
FROM Product
GROUP BY GroupID) AS p ON p.GroupID = g.GroupIDCode Snippets
SELECT g.*, p.Amt AS 'TotalCost', p.Amt * 0.1 AS 'GST'
FROM Group g
LEFT JOIN (SELECT GroupID, SUM(Price) AS Amt
FROM Product
GROUP BY GroupID) AS p ON p.GroupID = g.GroupIDContext
StackExchange Database Administrators Q#73849, answer score: 4
Revisions (0)
No revisions yet.