Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do CTEs use any space in tempdb?

Do CTEs use any space in tempdb or does it use memory exclusively?

I've tagged the question with both mssql 2005 and 2008 as I use both.

like image 623
deutschZuid Avatar asked Oct 18 '11 02:10

deutschZuid


People also ask

Do CTEs use tempdb?

Tempdb is a very special system database that is used to store temporary objects which are created by the users explicitly or by the internal system process. The following objects or operations use tempdb: Global and local temporary tables. Common table expressions (CTE)

Does CTE use memory?

Typical symptoms of CTE include: short-term memory loss – such as asking the same question several times, or having difficulty remembering names or phone numbers.

What are the drawbacks of CTEs?

Disadvantages of CTECTE members are unable to use the keyword clauses like Distinct, Group By, Having, Top, Joins, etc. The CTE can only be referenced once by the Recursive member. We cannot use the table variables and CTEs as parameters in stored procedures.

What is using my tempdb space?

TempDb is being used by a number of operations inside SQL Server, let me list some of them here: Temporary user objects like temp tables, table variables. Cursors. Internal worktables for spool and sorting.


1 Answers

I'll try not to copy/paste MSDN

It doesn't matter.

A CTE is independent of query execution: it is only a language construct. Think of it as neat derived table or subquery.

This means that except for recursive CTEs (see later), all CTEs can be coded inline. If you use the CTE code once, it is for readability. If you use the CTE twice or more, then it is defensive: you don't want to make a mistake and have the derived table different each use.

Where a CTE is used twice or more, then that code will be executed twice or more. It won't be executed once and cached in tempdb.

Summary: it may or may not, just like if the code was inline.

Note: a recursve CTE is simply a derived table inside a derived table inside a derived table inside a a derived table inside a der... so same applies.

You can see this in Tony Rogerson's article. The use of tempdb would happen anyway if coded inline. He also notes that using a temp table can be better because of the "macro" expansion I explained above

FYI: the same applies to views. Just macros.

like image 86
gbn Avatar answered Sep 29 '22 06:09

gbn