I think this question needs to be better explored. There is no general answer, as this depends on the implementation of each database engine. The SQL language is declarative. You say what wants and not how to get. The how is left over by the engine. In some cases it is possible to give a hint to the engine, but not to radically change the way it works.
So, what I'm going to show here are tests I did in SQL Server 2005.
My tests were based on two queries. The first one is in the question. The second (cross-join) is in this response. See below:
Query 1
SELECT
NUMBER,
(SELECT COUNT(*) FROM NUMBERS)
FROM
NUMBERS
Query 2
SELECT
NUMBER,
TOTAL.T
FROM
(SELECT COUNT(*) T FROM NUMBERS) TOTAL,
NUMBERS
Numbers Table
Creating and populating the Numbers table (999999 records) can be seen below.
CREATE TABLE [dbo].[Numbers](
[Number] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Number] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--1 milhão de registros são adicionados
insert into Numbers(Number)
select top 1000000 row_number() over(order by t1.number) as N
from master..spt_values t1
cross join master..spt_values t2
Hypothesis
The hypothesis is that a SELECT COUNT (*) is not made for each record in the case of Query 1 .
It's a simple optimization that SQL Server programmers would not let go of. Note that (SELECT COUNT (*) FROM NUMBERS) is completely independent of the query. The value of it can be calculated once, stored and just put in the SQL return (as if it were a constant).
Analysis
The image below shows the Query 1 execution plan:
ThisimageshowstheQuery2executionplan:
TheonlydifferenceisanoperatorcalledComputerScalar.Therestoftheoperatorsisexactlythesameinthepositionwithinthetreeandinthevaluescomputed/estimatedbytheSQLServerplanner.ComputerScalarcostsanestimated2%forthiscase.
IwentalittlefurtheranddidananalysisusingtheSQLServerProfile.Seethereturn:
ThemostimportantthingtonotehereisthatthenumberofReads(readings)ofthetwoqueriesisthesame.TheQuery1timeisabitlongerduetotheCPUconsumption(alsoslightlylarger).CertainlyitisComputerScalaroperatorshownabove.
Stillintheprofile,Icheckedthecosttoexecuteonlythestatementbelow:
SELECTCOUNT(*)FROMNUMBERS
Theresultcanbeseenbelow:
Conclusion
In the foregoing, you can see that the assumption raised is correct and that SQL Server 2005 Planner in the context , did not perform a count operation to each line returned. Quite possibly the other bank engines also optimize queries like this one, in order to avoid unnecessary processing.
Note that Query 2 still performs slightly better and may be indicated by this. However, it should be made clear that the purpose here was not to compare the performance of the two queries, but to show that a query count (*) is not made in SQL Query 1 .