Quantcast
Channel: Active questions tagged cte - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 207

SQL Server CTE improves query performance due to larger memory grant?

$
0
0

I have a large table (20M+) which has a clustered index on COBID.

When I run this query:

SELECT * FROM dbo.mytableWHERE COBId = 20240723  AND TradeID = '123456'

it completes in around 10 seconds.

However I break things down into steps (this is a very simplistic example) and I run this instead:

WITH cte AS (    SELECT *     FROM dbo.mytable    WHERE COBId = 20240723)SELECT * FROM cteWHERE TradeID = '123456'

it completes in 5 seconds. This holds true across nearly every large table in my database, and time savings can be up to 90%.

In this example comparing the query plans between the 2 they both use a clustered index seek, one just returns much faster.

I did notice that it may be due to the CTE query having a much larger memory grant (6400KB vs 130KB)

Doing some googling around and i can't really see any reference to the fact that using a CTE like this can (sometimes) result in large performance gains.

Can anyone add some colour to this?


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>