wasAsked.

What are Temp Tables and CTEs?

Impetus · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

Both hold intermediate results in SQL, but they behave very differently. Temporary tables (#Temp) - Real tables created in tempdb: CREATE TABLE #RecentOrders (OrderId INT PRIMARY KEY, CustomerId INT, Total DECIMAL(18,2)); INSERT INTO #RecentOrders SELECT OrderId, CustomerId, Total FROM Orders WHERE OrderDate >= DATEADD(DAY, -30, GETDATE()); or SELECT ... INTO #RecentOrders FROM ... - Local temp tables (#name) are visible to the current session and dropped automatically when the session or stored procedure ends; global temp tables (##name) are visible to all sessions. - Persist across multiple statements in the batch or procedure. - Can have indexes, constraints and statistics, so the optimiser can make good plans for large intermediate data. - Can be updated, inserted into and joined many times. - Cost: physical writes to tempdb and possible recompilations. CTEs (Common Table Expressions) - Named, temporary result sets defined with WITH, valid only for the single statement that follows: WITH RecentOrders AS (SELECT OrderId, CustomerId, Total FROM Orders WHERE OrderDate >= DATEADD(DAY, -30, GETDATE())) SELECT CustomerId, SUM(Total) FROM RecentOrders GROUP BY CustomerId; - Not stored: SQL Server expands the CTE into the query like an inline view. If referenced several times, the logic may run several times. - Cannot be indexed. - Support recursion (hierarchies, sequences). - Great for readability and for window-function filtering or deleting duplicates. When to choose which - CTE: improving the readability of a single complex query, recursive queries, small to moderate intermediate results used within one statement. - Temp table: large intermediate results reused in several statements, when indexing helps performance, when breaking a very complex query into steps helps the optimiser, or for staging data in batch processes. Also compare table variables (DECLARE @t TABLE (...)) - Scoped to the batch; historically poor cardinality estimates (improved in SQL Server 2019 with deferred compilation); limited indexing options; good for small row sets. Example decision: "For a monthly report joining a million rows across several steps, I loaded filtered data into an indexed #temp table first, which reduced execution time significantly compared with a long chain of CTEs referencing each other multiple times."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics