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 ««1234»»»

Simplify Large Queries with Temporary Tables, Table Variables and CTEs Expand / Collapse
Author
Message
Posted Tuesday, August 9, 2011 6:10 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, February 4, 2013 4:48 AM
Points: 3, Visits: 23
It is a concept to solve complex queries

Thanks
Post #1156753
Posted Tuesday, August 9, 2011 6:45 AM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Monday, January 27, 2014 10:14 AM
Points: 1,322, Visits: 1,091
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
Post #1156784
Posted Tuesday, August 9, 2011 6:57 AM


Say Hey Kid

Say Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey Kid

Group: General Forum Members
Last Login: 2 days ago @ 7:50 AM
Points: 705, Visits: 3,019
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
Post #1156800
Posted Tuesday, August 9, 2011 7:02 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: 2 days ago @ 9:22 AM
Points: 136, Visits: 625
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

Post #1156805
Posted Tuesday, August 9, 2011 7:19 AM


SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Today @ 9:57 AM
Points: 4,406, Visits: 6,270
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 at GMail
Post #1156824
Posted Tuesday, August 9, 2011 7:59 AM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Tuesday, September 30, 2014 12:09 AM
Points: 30, Visits: 493
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
Post #1156857
Posted Tuesday, August 9, 2011 8:02 AM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: Tuesday, October 14, 2014 12:10 PM
Points: 1,414, Visits: 4,541
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


https://plus.google.com/100125998302068852885/posts?hl=en
http://twitter.com/alent1234
x-box live gamertag: i am null
[url=http://live.xbox.com/en-US/MyXbox/Profile[/url]
Post #1156864
Posted Tuesday, August 9, 2011 8:55 AM


Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Monday, March 18, 2013 5:14 AM
Points: 15, Visits: 47
sometimes the prettier solutions perform far worse

unfortunately SQL Server cares not one jot for the aesthetics of your code
Post #1156936
Posted Tuesday, August 9, 2011 8:56 AM


SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Today @ 9:57 AM
Points: 4,406, Visits: 6,270
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!!


Best,

Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru at GMail
Post #1156940
Posted Tuesday, August 9, 2011 9:58 AM


SSCoach

SSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoachSSCoach

Group: General Forum Members
Last Login: Today @ 6:00 PM
Points: 17,825, Visits: 15,758
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
Post #1157016
« Prev Topic | Next Topic »

Add to briefcase ««1234»»»

Permissions Expand / Collapse