Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server with clause versus temporary table

I could either do

select * into #randomTenUsers from
(select top 10 * from users)x    

select * from #randomTenUsers

OR

WITH randomTenUsers   as (select top 10 * from users)    

select * from randomTenUsers

From what I understand WITH statement also creates a temporary result set.

Is there a reason why WITH should be preferred over temp tables or vice versa?

like image 406
Foo Avatar asked May 22 '13 16:05

Foo


People also ask

Does WITH clause create a temporary table?

The WITH clause is an optional clause used to contain one or more common table expressions (CTE) where each CTE defines a temporary table that exists for the duration of the query. Each subquery in the WITH clause specifies a table name, an optional list of column names, and a SELECT statement.

Is it better to use table expressions or temporary tables?

As far as when to use each, they have very different use cases. If you will have a very large result set, or need to refer to it more than once, put it in a #temp table. If it needs to be recursive, is disposable, or is just to simplify something logically, a CTE is preferred.

What are the differences between temporary table and with?

While TEMP table is transient only for the current session, WITH is always re-evaluated.

What is the alternative for temporary table in SQL Server?

A valuable alternatives for the SQL temp table and table variable are SCHEMA_ONLY Memory-Optimized tables and the Memory-optimized Table Variable, where the data will be completely stored in the memory without the need to touch the TempDB database, providing the best data access performance.


1 Answers

From what I understand WITH statement also creates a temporary result set.

No it does not. Using a CTE will not create a "temporary result set". There might be reasons for a query to create work tables but just because you are using a CTE is not one of them.

These two queries have an identical query plan and none of them creates a temporary result like a temp table in tempdb.


with randomTenUsers as
(
  select top 10 *
  from users
)    
select * 
from randomTenUsers;

select * 
from (
     select top 10 * 
     from users
     ) x;

As marc_s said in the comment, what you should use depends on what you want to do. There are situations where creating a temp table makes perfect sense and there are situations where it is completely unnecessary.

like image 141
Mikael Eriksson Avatar answered Oct 11 '22 08:10

Mikael Eriksson