I have a query generated by QueryFolding of PowerBi Desktop. I was trying to understand how it works. I can see that there is a big query, with nested sub-selects.
If I run this query, this took about 1 seconds to complete. But when I run the second query, i.e. the inner-one of the multiple subselects, this tooks about two minutes.
So, how does SQL server handles the TOP 1000 or the WHERE in a sub-select? Why is the inner query slower than the whole query?
Thanks!!
Whole Query (Faster)
select top 1000
[_].[NOMBRE_1] as [NOMBRE_1],
[_].[SUSCRIPCIO] as [SUSCRIPCIO],
[_].[ANOMES] as [ANOMES],
1 as [Rut]
from
(
select [_].[NOMBRE_1],
[_].[SUSCRIPCIO],
[_].[ANOMES]
from
(
select [NOMBRE_1],
[SUSCRIPCIO],
[ANOMES]
from [dbo].[TABLE] as [$Table]
) as [_]
where [_].[SUSCRIPCIO] >= convert(datetime2, '2020-01-01 00:00:00') and [_].[SUSCRIPCIO] <= convert(datetime2, '2020-02-01 00:00:00')
) as [_]
Inner SubSelects (Slower)
select [NOMBRE_1],
[SUSCRIPCIO],
[ANOMES]
from [dbo].[TABLE] as [$Table]