SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Simplify Large Queries with Temporary Tables, Table Variables and CTEs


Simplify Large Queries with Temporary Tables, Table Variables and CTEs

Author
Message
kathirvelinfo
kathirvelinfo
Forum Newbie
Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)Forum Newbie (7 reputation)

Group: General Forum Members
Points: 7 Visits: 23
It is a concept to solve complex queries

Thanks
James Goodwin
James Goodwin
Ten Centuries
Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)Ten Centuries (1.4K reputation)

Group: General Forum Members
Points: 1421 Visits: 1107
A good introduction to the alternatives, but I take exception to the statement that "it is impractical to create new views for every query you write." Certainly, you wouldn't create a new view for EVERY query, just as you won't use Temp Tables or CTEs in EVERY query.

For the most part CTEs replace subqueries and potentially make the queries more readable, but don't seem to offer much in the way of performance improvement. They do this by allowing reuse (like a view), but also by keeping the entire query contained. This can be good but also reduces code reuse--a view can be used in more than one query. Their main functional benefit over a view is their ability to use the parameters in a SP. This benefit is shared by a TVF, however there are limitations to what can be done in a function, but again Functions are available for code reuse while CTEs are not.

Any design decision will, of course, need to be made in the context of a specific need, balancing code reuse, performance, maintainability, and security.

As Always YMMV,
--
JimFive
Rich Mechaber
Rich Mechaber
SSCommitted
SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)SSCommitted (1.6K reputation)

Group: General Forum Members
Points: 1561 Visits: 3665
Table variables and CTEs are stored in memory (if sufficient memory is available), while temporary tables are always stored on disk.


This is untrue, or at best misleading. From http://support.microsoft.com/kb/305977:
Q4: Are table variables memory-only structures that are assured better performance as compared to temporary or permanent tables, because they are maintained in a database that resides on the physical disk?

A4: A table variable is not a memory-only structure. Because a table variable might hold more data than can fit in memory, it has to have a place on disk to store data. Table variables are created in the tempdb database similar to temporary tables. If memory is available, both table variables and temporary tables are created and processed while in memory (data cache).
(Emphasis added).

Several people have written about this. Here's one, here's another.

Rich
the sqlist
the sqlist
SSC Veteran
SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)SSC Veteran (240 reputation)

Group: General Forum Members
Points: 240 Visits: 724
A temporary table is available as long as the database connection with which it was executed is still open. If it is declared with the "##" prefix, it is a global variable available to other sessions. If it is declared with the "#" prefix, it is a local variable available only in the current session.


Worth mentioning here that in the case of global temp tables(##), which actually are kind of rarely used, they remain active until there is at least one open connection that uses them, regardless if it is the one that created it or another. The local temp tables(#) are only available to the connection that created them, of course.

Don't just give the hungry man a fish, teach him how to catch it as well.

the sqlist
TheSQLGuru
TheSQLGuru
SSChampion
SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)

Group: General Forum Members
Points: 12679 Visits: 8563
1) The primary if not only reason do break down a complex query into multiple steps with interim storage (using TEMPORARY TABLES, NOT TABLE VARIABLES as discussed in number 2 below) is to ensure optimal performance of said query. You absolutely should NOT break down a single query into multiple steps just for 'human readability'.

2) Table variables should almost NEVER be used. The two exceptions I can think of are if you have a VERY high call situation where recompilations related to temp table activity are causing performance degredation or if you need interim data to remain in place for auditing purposes after a transaction rollback. Others mention performance problems from table variables with lots of rows. Well, I can show you an example that gives bad performance with just a SINGLE row in a table variable.

Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
Josh Ashwood
Josh Ashwood
Valued Member
Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)Valued Member (54 reputation)

Group: General Forum Members
Points: 54 Visits: 535
One annoyance about the query optimizer in SQL Server is that sometimes the prettier solutions perform far worse, eg. sometimes ugly procedural T-SQL with temp table use etc can perform far better than a single, succinct SQL SELECT statement using CTE's etc..

I think the optimizer could do a better job with CTE definitions in sql server..

Or maybe its just my queries :-P
alen teplitsky
alen teplitsky
SSCrazy
SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)SSCrazy (2.8K reputation)

Group: General Forum Members
Points: 2808 Visits: 4674
probably just me but i try to avoid temp tables as much as i can only because i don't like the I/O overhead of using them. One developer i knew used to use views all the time. i think he went way over board with them because one time i was troubleshooting performance issues with one of his processes and it took me hours to dig into the multiple levels of views that he wrote. most of them only returned a few rows.

i don't write a lot of SQL code but end up reading it and most of the really long queries have lots of temp tables. makes it a PITA to find out where the problem is and a lot of times running an estimated execution plan is useless because there is no temp table yet. if there was a view instead of a temp table it would probably make things a lot easier

caveat - like everything in SQL server there is no black or white and different things work in different environments and workloads. temp tables have their uses in some cases
ben.reese
ben.reese
SSC Rookie
SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)SSC Rookie (25 reputation)

Group: General Forum Members
Points: 25 Visits: 47
sometimes the prettier solutions perform far worse

unfortunately SQL Server cares not one jot for the aesthetics of your code
TheSQLGuru
TheSQLGuru
SSChampion
SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)

Group: General Forum Members
Points: 12679 Visits: 8563
alen teplitsky (8/9/2011)
probably just me but i try to avoid temp tables as much as i can only because i don't like the I/O overhead of using them. One developer i knew used to use views all the time. i think he went way over board with them because one time i was troubleshooting performance issues with one of his processes and it took me hours to dig into the multiple levels of views that he wrote. most of them only returned a few rows.

i don't write a lot of SQL code but end up reading it and most of the really long queries have lots of temp tables. makes it a PITA to find out where the problem is and a lot of times running an estimated execution plan is useless because there is no temp table yet. if there was a view instead of a temp table it would probably make things a lot easier

caveat - like everything in SQL server there is no black or white and different things work in different environments and workloads. temp tables have their uses in some cases


Outside of improper indexing and scalar UDF usage some of the biggest performance wins I have done for clients is breaking down immensely complex single SELECT statements into interim queries using temporary tables for storage.

Oh, and I get paid by the hour, so I go KAAACCHHHIIIIIIINNNGGGG when I see a client with a ton of nested views that I have to wade through!! Cool

Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
SQLRNNR
SQLRNNR
SSC-Dedicated
SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)SSC-Dedicated (32K reputation)

Group: General Forum Members
Points: 32855 Visits: 18559
Josh Ashwood (8/9/2011)
Nice article, and definitely on topic for real database developers...

However the more relevant question we are often faced with is what performs better - table variables, temp tables, or CTE's or leave the damn thing in one huge query ?

An 'It depends' answer would be ok, if expanded on!


I'd agree. Showing some examples with finite variables and specific environment described would be helpful.



Jason AKA CirqueDeSQLeil
I have given a name to my pain...
MCM SQL Server, MVP


SQL RNNR

Posting Performance Based Questions - Gail Shaw

Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search