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?
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.
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.
While TEMP table is transient only for the current session, WITH is always re-evaluated.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With