Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one have better performance : Derived Tables or Temporary Tables

Tags:

Sometimes we can write a query with both derived table and temporary table. my question is that which one is better? why?

like image 344
masoud ramezani Avatar asked Feb 24 '10 13:02

masoud ramezani


People also ask

Which is faster temp table or table?

Temp tables are better in performance. If you use a Table Variable and the Data in the Variable gets too big, the SQL Server converts the Variable automatically into a temp table. It depends, like almost every Database related question, on what you try to do. So it is hard to answer without more information.

Which is better in performance CTE vs temp table?

Looking at SQL Profiler results from these queries (each were run 10 times and averages are below) we can see that the CTE just slightly outperforms both the temporary table and table variable queries when it comes to overall duration.

What is the advantage of using a temporary table instead of a table?

Temporary tables behave just like normal ones; you can sort, filter and join them as if they were permanent tables. Because SQL Server has less logging and locking overheads for temporary tables (after all, you're the only person who can see or use the temporary table you've created), they execute more quickly.


1 Answers

Derived table is a logical construct.

It may be stored in the tempdb, built at runtime by reevaluating the underlying statement each time it is accessed, or even optimized out at all.

Temporary table is a physical construct. It is a table in tempdb that is created and populated with the values.

Which one is better depends on the query they are used in, the statement that is used to derive a table, and many other factors.

For instance, CTE (common table expressions) in SQL Server can (and most probably will) be reevaluated each time they are used. This query:

WITH    q (uuid) AS         (         SELECT  NEWID()         ) SELECT  * FROM    q UNION ALL SELECT  * FROM    q 

will most probably yield two different NEWID()'s.

In this case, a temporary table should be used since it guarantees that its values persist.

On the other hand, this query:

SELECT  * FROM    (         SELECT  *, ROW_NUMBER() OVER (ORDER BY id) AS rn         FROM    master         ) q WHERE   rn BETWEEN 80 AND 100 

is better with a derived table, because using a temporary table will require fetching all values from master, while this solution will just scan the first 100 records using the index on id.

like image 136
Quassnoi Avatar answered Nov 23 '22 17:11

Quassnoi