CTE vs Temp Table vs Subquery in SQL Server: Which Is Faster?
"Should I use a CTE or a temp table?" is one of the most common SQL Server questions, and the answer is often misunderstood. The key fact: a CTE is just a named query, not a stored result. Once you know that, choosing becomes straightforward. The three options -- 1. Subquery (derived table) SELECT d.DepartmentId, d.TotalPay FROM (SELECT DepartmentId, SUM(Amount) AS TotalPay FROM dbo.Payment GROUP BY DepartmentId) AS d WHERE d.TotalPay > 100000; -- 2. Common table expression (CTE) WITH DeptPay AS ( SELECT DepartmentId, SUM(Amount) AS TotalPay FROM dbo.Payment GROUP BY DepartmentId ) SELECT DepartmentId, TotalPay FROM DeptPay WHERE TotalPay > 100000; -- 3. Temporary table SELECT DepartmentId, SUM(Amount) AS TotalPay INTO #DeptPay FROM dbo.Payment GROUP BY DepartmentId; SELECT DepartmentId, TotalPay FROM #DeptPay WHERE TotalPay > 100000; CTEs and subqueries perform the same SQL Server expands a non-recursive CTE into the main query before optimizing, ex...