Temp Table And CTE

Temp Table And CTE

Database

June 28, 2024

This blog explores the differences between Temp Tables and Common Table Expressions (CTEs).

Temp Tables

Temp Tables are temporary tables that are created in the database at runtime and are automatically dropped when the session ends.

Example of creating a Temp Table:

CREATE TABLE #temptable (customerid INT NOT NULL PRIMARY KEY, lastorderdate DATETIME NULL);
INSERT INTO #temptable
SELECT customerid, MAX(orderdate) AS lastorderdate
FROM sales.SalesOrderHeader
GROUP BY customerid;

Common Table Expressions (CTEs)

CTEs are temporary result sets that are defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

Example of using a CTE:

WITH t (customerid, lastorderdate) AS
(
    SELECT customerid, MAX(orderdate)
    FROM sales.SalesOrderHeader
    GROUP BY customerid
)
SELECT *
FROM sales.SalesOrderHeader soh
INNER JOIN t ON soh.customerid = t.customerid AND soh.orderdate = t.lastorderdate;

Performance Considerations

However, if you have a very large result set or need to refer to it multiple times, a temporary table is preferred.

Remember that CTEs are not valid beyond the specific query where they are defined.

In summary, choose a temporary table when reusing data or dealing with large result sets, and use a CTE for readability or recursive queries.

Keep in mind the scope and limitations of each approach!

Copyright 2024