SQL Server version:
Microsoft SQL Server 2019 (RTM-CU8-GDR) (KB4583459) - 15.0.4083.2 (X64)Nov 2 2020 18:35:09Copyright (C) 2019 Microsoft CorporationEnterprise Edition: Core-based Licensing (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: ) (Hypervisor)
I have one query which is completing in less than a second, with 5 million records in both table used. Actual Execution plan shows Index Seek for both the tables and both table reads 1 or 2 rows.
But, when convert same query to CTE, it is taking around 2min. The Actual Execution Plan shows Index Scan and reads all 5 million rows.
Until now, I was under the impression that for normal query, it doesn't matter if query is within a CTE or not. Even same nested query is also very slow.
What could be affecting it?
Actual query is:
select ca.inst_bs as Base, dateadd(mi,ROW_NUMBER() over (partition by i2.idcse,i2.idpln order by i2.dtdue,i2.id),i2.dtdue) as d1, i2.id, ca.id as idcse, i2.dtdue from tbl_cse ca with(nolock) join tbl_Inst i2 with(nolock) on i2.idcse = ca.idwhere i2.idcse = 3169
Query converted to CTE is:
with tt as ( select ca.inst_bs as Base, dateadd(mi,ROW_NUMBER() over (partition by i2.idcse,i2.idpln order by i2.dtdue,i2.id),i2.dtdue) as d1, i2.id, ca.id as idcse, i2.dtdue from tbl_cse ca with(nolock) join tbl_Inst i2 with(nolock) on i2.idcse = ca.id)select * from tt where idcse = 3169
Actual Execution Plan for performant query: Query.sqlplan
Fast Plan visualized on Paste The Plan
Actual Execution Plan for slow query using CTE: CTE.sqlplan
Slow Plan visualized on Paste The Plan
If I convert my normal query to a view and use idcse = 3169
criteria with the view, it is working slow, same as CTE.
For a temporary solution, I created a table-valued function that accepts the criteria and it is working as expected to give an index seek. I need to keep checking for a complete solution because many of my queries and views use a CTE with row_number
.