r/SQLServer • u/ScaryDBA Microsoft MVP • Aug 01 '16
There Is No Difference Between Table Variables, Temporary Tables and Common Table Expressions
http://www.scarydba.com/2016/08/01/there-is-no-difference-between-table-variables-temporary-tables-and-common-table-expressions/11
u/eshultz Aug 01 '16
Your title made me fly into a tiny rage as I waited for the link to load.
6
u/ScaryDBA Microsoft MVP Aug 01 '16
I was worried that people might get actually upset. I tried to clarify fast that it wasn't true.
1
u/Lucrums Aug 01 '16
Heh, I read the title and was about to try to be polite while being annoyed at the mis-information. Then I read the author and I thought you were going for a luring title to get people to read. I'm glad the information is good, there's enough bad information about what we do already.
1
5
u/eshultz Aug 01 '16
You should show an example with more than a couple thousand rows - perhaps 100k - to really show how different the performance can be. Also wouldn't hurt to show how painful CTEs that perform computation and/or reference other CTEs can be, compared to the same techniques with temp tables.
My strategy is typically to use temp tables wherever possible, unless I need recursion or am prohibited from doing so such as inside a function. There's a snippet of code that is very invaluable. Rather than relying on the drop table #mytemptable to execute at the end of the batch, use something like this at the top:
if object_id('tempdb..#mytemptable') is not null
drop table #mytemptableThat way, the temp table's existence is not going to be dependent on your last execution of the script (such as if an error occurred in the batch and the table was not dropped for some reason).
2
u/ScaryDBA Microsoft MVP Aug 01 '16
Good stuff. Lots of examples can be made to show how any one of the constructs can work better than the others, depending on the situation. I just wanted a really simplistic example to show that, regardless of how simplistic I made it, there are distinct differences in how each piece of code behaves.
4
Aug 01 '16
[removed] — view removed comment
2
Aug 01 '16
my god, thats smart. never thought about it.
1
Aug 01 '16
[removed] — view removed comment
2
u/Lucrums Aug 01 '16
True but needs the new CE so SQL 2014+
2
Aug 01 '16
[removed] — view removed comment
3
u/Lucrums Aug 01 '16
Well you kind of can. Downside is its long winded. Where I need very little variance and super tight control I use a CTE per table to query. Usually I use a CTE for groups of tables. Each CTE has a top statement based on a variable. Then you can use the query hint optimise for. Using a much simpler query as an example:-
DECLARE @top int; SELECT TOP ( @top ) * FROM dbo.table OPTION( OPTIMIZE FOR( @top = 25000 ) );The optimiser should always predict 25000 rows. The PITA is if you need to do this for more than a couple of tables/groups. Also you have the natural drawback of CTEs. The other way I have done this is with iTVFs. Again the usual drawbacks remain.
I wish there were better hints but this can suffice at times.
2
u/alinroc 4 Aug 05 '16
I didn't see it in an article but I'm pretty sure Wayne Sheffield mentioned that guideline in his appearance on the SQL Data Partners podcast a few weeks ago. It probably comes up in his presentation Table Vars & Temp Tables – What you NEED to Know! which I think I caught at a Summit.
Which also means he has probably written an article or blog post or two about it :)
1
u/Lucrums Aug 01 '16
Shouldn't throw away the plan with the right settings. Depends on what you need though. If you prevent auto create and update of stats the plan should remain. Although that has other knock on effects. All depends on what you need really.
3
Aug 01 '16
[removed] — view removed comment
2
u/Lucrums Aug 01 '16
I think I'm too tired to understand but I think that means that if you create a temp table in dynamic SQL then your plan is SPID specific. Which if true, then I didn't know that. Pretty cool.
I suspect that the changes they're talking about there are when you exceed a stats recompile threshold or do something like whack an index or some stats on.
On that point if you amend the table after create then the table can't be templates so you'll possibly get more TempDB contention issues anyway. It's a trade off between the increased logging of creating all indexes up front and allocation page contention. It should also be noted that SQL Server 2014 had some optimisations to TempDB logging. As such I often favour indexes up front, declared as part of the table definition. For completeness that means you can on use a PK and unique indexes. I rarely find any need for included columns and can add the PK to make other indexes unique (This happens internally anyway) so I'm good with that.
Anyway bed time for me. Would love to stop up and chat but hey. Hopefully this is still going on in the morning :)
4
u/sandy_virginia_esq Aug 01 '16
One word:indexing
1
u/ScaryDBA Microsoft MVP Aug 02 '16
Yes. Absolutely. The example even shows how indexes behave differently on the different objects.
3
u/MC_RowdyV Aug 01 '16
I actually heard something very close to this at SQLSaturday in Houston. Presenter referred to them as "at sign tables" and "hashtag tables" and said that it didn't matter which you used... sigh
2
2
u/Lucrums Aug 01 '16
In a small low tran rate environment it doesn't :) it all depends on what you're trying to do and what you're dealing with at the end of the day.
Too many people think their one environment is the same as the whole world and that they can extrapolate to your environment from theirs.
5
u/MC_RowdyV Aug 01 '16
While I agree, it's important to offer those caveats when teaching students with diverse environments back home. It's not so much that he wasn't technically correct, just that he needed to offer context in which he was correct.
1
u/Lucrums Aug 01 '16
Absolutely agree. Did you raise the point out of interest? I'd have asked a question where it just doesn't fit his model of the world. There are a lot of people who will just believe what that person said.
It's a shame we can't dial down bad advice. I know I gave bad advice in the past, and probably still do accidentally. I always aim to provide the best advice I can and keep learning. Hopefully that presenter corrects themselves in future.
0
Aug 02 '16
[deleted]
1
u/Lucrums Aug 02 '16
I'm not even sure if I've ever heard that before. I think it's a funny term and maybe shows that the speaker didn't have the best knowledge. I wonder what the speaker would have called global temp tables?
"You see these hashtag hashtag tables? They're a whole different breed."
That would get annoying real fast :)
2
u/da_chicken Aug 02 '16
The one I always remember is that the cardinality estimator for table variables always assumes the variable has 1 record in it, and I don't believe this changed with Server 2014. On temp tables it actually works normally. So it's much more likely that a table variable will end up with a poor query plan.
1
u/ScaryDBA Microsoft MVP Aug 02 '16
Yep. Although not necessarily a poor plan, just one based on a small row set, always. If you have a small row set, great. If you don't, not great.
1
Aug 02 '16
[removed] — view removed comment
1
u/da_chicken Aug 02 '16
Oh did they? Hm. I was sure I'd tested it. Maybe the DB I was working with still had a lower compatibility level. I guess that's better than 1. Still somewhat frustrating that table variables don't track that sort of thing.
13
u/StopThinking Aug 01 '16
well the title sure got my attention! nice article.