1

I have code like

select count(*) from(
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1) x

select * from(
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1) x
where x.col1 > 10

I'm selecting and joining same tables with same columns twice. If i do it like:

declare @table table(col1 int,col2 int,col3 varchar,col4 int)
insert into @table(col1,col2,col3,col4) select * from (
select t1.col1, t1.col2, t1,col3, t2.col2 from table1 t1
left join table2 t2 on t1.col1=t2.col1
) x
select count(*) from @table
select * from @table where col1>10

which one would have better performance? creating temp table and reusing it multiple times or just selecting multiple times?

4
  • 2
    Why not try it both ways, and find out? Commented Mar 30, 2014 at 4:18
  • @JohnSaunders this case happens a lot. I don't want results for a specific case. I want to know the difference in general. Commented Mar 30, 2014 at 4:20
  • 4
    In general, performance is specific. Commented Mar 30, 2014 at 4:21
  • Well, in general, if computing the sub-SELECT is time-consuming, and you will use that sub-SELECT in many different queries, then obviously it must be faster to put the results in a temporary table. But you know this already. Commented Mar 30, 2014 at 4:22

1 Answer 1

5

I will not suggest selecting multiple time same query, if data are not changing on the table at run time and also number of rows selected are under 10000-15000 (depending on resources). Better is if we can hold once selected data in cache and make what ever manipulation required. Variable table have benefit over temp table in such case because when scope of query is over, resources utilized by variable table are also released.

Sign up to request clarification or add additional context in comments.

3 Comments

That in and of itself is not a good reason to choose table variables over temporary tables. This answer explains very clearly how you should make that choice.
Yes, that is right but Temp table behave as real table and is accessible out of the current scope, so when multiple user access same procedure then conflict may arise while inserting and deleting records.
Only global temporary tables (prefixed ##). Local temporary tables (prefixed #) are not available outside your session, even from sessions on the same connection/with the same username. Local temp tables are dropped when your session ends. In addition, table variables cannot have indexes (other than primary keys and unique constraints). This generally makes table variables unsuited to large data sets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.