Can anyone break it down in plain English the performance difference between using temp tables vs. CTE's vs. table variables in MSSQL. I have used temporary tables quite frequently and have started using CTE's just because of the clear syntax but I have found them to be slower. I think that temp tables are using system memory and that is why they seem fast but may be a bottleneck if trying to do multiple jobs. Table variables I have used sparingly and do not know a great deal about. Looking for some advice from the guru's out there!

- 5,753
- 72
- 57
- 129

- 3,163
- 11
- 36
- 47
-
I believe temp tables (#table) are stored in the system db, so not necessarily in memory (and also they inherit server defaults for certain properties, like collation). But the main reason I commented was to say your tag is mysql, not mssql. – tomfumb Aug 15 '11 at 23:41
-
@tomfumb, they are stored in the tempdb system database. – Aug 15 '11 at 23:54
3 Answers
CTEs are performance-neutral. They simplify a query for the developer by abstracting out SQL statements - usually complicated JOINs or built-in functions applied to fields. The database engine just in-lines the CTE into the query that uses it. So, the CTE itself isn't "slow", but you may find you are having better performance with temp tables because the database engine is creating better query plans on the queries using the temp tables.

- 6,497
- 4
- 31
- 54
This question is well covered in Books Online, MSDN and this site.
About temp tables and table variables you can read here What's the difference between a temp table and table variable in SQL Server?. There you will find that in many cases temp tables cause recompilation of a procedure which is their main disadvantage.
CTEs are well described here http://blogs.msdn.com/b/craigfr/archive/2007/10/18/ctes-common-table-expressions.aspx

- 1
- 1

- 3,806
- 3
- 34
- 49