If I execute the following query in SQL Server 2008 R2, will the count(*) aggregate be determined only once for OUTER SELECT query or it will repeat for every record in OUTER SELECT?
I was guessing that SQL Server would be intelligent to see that the same calculation is being repeated and so it would do this calculation only once for optimization purpose. The value of TotalCount in query below is going to be the same for all rows in outer query.
SELECT
p.ProductId, p.ProductName,
(select count(*) from Products p1) as TotalCount
FROM Products p
No, you’re expecting too much from SQL Server. Also: the query processor really cannot be sure that this value won’t be changing over time – so it cannot really “optimize” this for you.
For every single row, this subquery will be executed once.
So if your
SELECTstatement will return 10 million rows, this count will be determined 10 million times.If you don’t want that, you can always run the
select count(*)..once before the query and store the value into a SQL variable, and select that variable in your query: