Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

CTE results storage same as temp table? Expand / Collapse
Posted Sunday, January 26, 2014 5:46 PM


Group: General Forum Members
Last Login: Friday, April 11, 2014 6:12 PM
Points: 197, Visits: 550
Simple question, are the results of a CTE stored in the same place as a temp table (tempdb)?

Post #1534832
Posted Sunday, January 26, 2014 6:08 PM



Group: General Forum Members
Last Login: Today @ 4:00 PM
Points: 35,967, Visits: 30,258
smallmoney (1/26/2014)
Simple question, are the results of a CTE stored in the same place as a temp table (tempdb)?


As with a View or any query, for that matter, they might not be stored at all. Proof of that is if you call the CTE twice as a self join. If you look at the execution plan, you'll see that the CTE actually had to run twice. Any interim storage required by a query, for a working table to support a hash join for example, will make use of TempDB.

That being said, TempDB is NOT disk only. If the optimizer can and does allocate memory for the task, the TempDB part of it will be done in memory. Similarly (and just to be sure), Table Variables are NOT memory only. They will spill to disk if they get too big.

--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

"Change is inevitable. Change for the better is not." -- 04 August 2013
(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1534833
Posted Monday, January 27, 2014 12:10 AM



Group: General Forum Members
Last Login: Today @ 11:52 AM
Points: 41,530, Visits: 34,446
CTEs aren't tables. They're named subqueries. Their results are not necessarily materialised or stored anywhere.

Gail Shaw
Microsoft Certified Master: SQL Server 2008, MVP
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

We walk in the dark places no others will enter
We stand on the bridge and no one may pass

Post #1534859
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse