CTE vs temp table performance in SQL Server is one of those evergreen debates that never seems to fade. The recent MSSQLTips article by Mehdi Ghapanvari compares both approaches and concludes that temp tables sometimes win because of better cardinality estimation (link). And yes! That’s absolutely true. Temp tables give the optimizer a materialized rowset with statistics, while CTEs are just syntactic sugar that inline into the main query, which directly influences CTE vs temp table performance in SQL Server under real workloads. This article takes a closer look at CTE vs temp tables and explains why both approaches behave differently under real SQL Server workloads.

Nobody measures the cost of creating and populating the temp table.

And that cost is not for free! It’s Recompiles, Tempdb Allocation, Logging, Metadata operations, and sometimes Latch Contention

CTE vs temp tables – Why this comparison matters

To compare the situation, I am also using the Stack Overflow database. Since I currently only have the version up to 2013, I am using different parameters; however, the behavior is identical. Please read Mehdi Ghapanvari’s blog post before reading my analysis. I am using the same queries (with different parameters) and focusing exclusively on the specific characteristics of the results! My analysis does NOT focus exclusively on the execution plans of the various approaches, but rather on the total costs and the reasons why the query optimizer performs an incorrect cost calculation!

To better evaluate the pros and cons of both variants, I use SQLQueryStress to ensure a broader data basis when analyzing the performance data. For this reason, I encapsulate both variants in stored procedures that are executed repeatedly by multiple processes within SQLQueryStress.

Temp table implementation and performance impact in SQL Server

/* Stored Procedure (WRAPPER) for temp table tests */
CREATE OR ALTER PROCEDURE dbo.temptable_test
AS
BEGIN
	SET NOCOUNT ON;

	DROP TABLE IF EXISTS #temp
 
	SELECT	u.CreationDate
	INTO	#temp
	FROM	dbo.users AS u
	WHERE	u.CreationDate > '2010-01-01'
	GROUP BY
			u.CreationDate
	HAVING	COUNT_BIG(*) > 1
	OPTION	(MAXDOP 4);
 
	SELECT	TOP (100)
			u.* 
	FROM	dbo.Users u 
			INNER JOIN #Temp t
			ON (u.CreationDate = t.CreationDate)
	ORDER BY
			u.Reputation,
			u.Id
	OPTION	(MAXDOP 4);
END
GO

CTE implementation and predictable performance behavior

/* Stored Procedure (WRAPPER) for CTE tests */
CREATE OR ALTER PROCEDURE dbo.cte_test
AS
BEGIN
	SET NOCOUNT ON;

	;WITH cte
	AS
	(
		SELECT	u.CreationDate
		FROM		dbo.users AS u
		WHERE	u.CreationDate > '2010-01-01'
		GROUP BY
				u.CreationDate
		HAVING	COUNT_BIG(*) > 1
	)
	SELECT	TOP (100)
			u.*
	FROM		dbo.users AS u
			INNER JOIN cte AS c
			ON (u.CreationDate = c.CreationDate)
	ORDER BY
			u.Reputation,
			u.id
	OPTION	(MAXDOP 4);
END
GO

If both procedures are executed and the obvious performance metrics (time) are compared, the solution from Mehdi Ghapanvariis is clearly faster. Objectively speaking, the solution using a temporary table is faster than using a CTE!

CTE always will run slower!

When comparing CTE vs temp tables, the most important factor is how each pattern interacts with tempdb, statistics, and concurrency. In real‑world systems, the performance gap between CTE vs temp tables becomes visible only under concurrent load.

Why temp tables often outperform CTEs in SQL Server

The reason for the advantage of using a temporary table lies in the misestimation of „estimated rows,“ which becomes evident in both approaches when examining the execution plan.

Execution plan differences: CTE vs temp tables

Wrong estimates after aggregation in FILTER operation
Execution Plan of CTE query

The FILTER operator shows wildly wrong estimates because SQL Server is aggregating on a datetime column, and the cardinality estimator applies a uniform distribution assumption that is catastrophically wrong for time‑series data.

This leads to:

  • Massive Memory Grants!
  • massively underestimated row counts
  • row‑goal behavior
  • wrong join choices
  • wrong parallelism distribution
  • and the FILTER operator showing “202 of 1,459,710 (0%)” although the upstream operator clearly produced millions of rows.

But what about the other required resources, and how does their consumption affect overall performance?

Concurrent benchmark: CTE vs temp tables under workload

I tested both scenarios under pressure by executing every wrapper procedure with 20 concurrent clients and 1,000 executions. I executed both variants under identical conditions using SQLQueryStress to compare the resources required for execution under load. The following metrics were taken into account:

  • CPU Queue Length
  • BATCH REQUESTS/s
  • RECOMPILES/s
  • TEMPDB (bytes written/s)

dbo.temptable_test – temp table workload behavior

The picture shows the Processor Queue Length usage over the runtime of the temp table test and has a peak value of 70 waiting processes waiting for CPU

During the 20‑client × 1000‑execution temp table benchmark, the Processor Queue Length shot up dramatically — peaking above 70.

it is an indicator that the workload was CPU‑saturated and that the scheduler was completely overwhelmed.

The Batch Requests/sec graph shows that once the temp‑table workload started, SQL Server was able to process far fewer batches than expected, indicating that the system was no longer keeping up with the incoming work

The Re‑Compilations/sec graph shows that once the temp‑table workload started, SQL Server began recompiling statements far more frequently, indicating that the engine was constantly rebuilding plans instead of executing them efficiently.

The sharp rise in TEMPDB write activity aligns directly with the drop in Batch Requests/sec and the spike in Re‑Compilations/sec, showing that the server spent more time allocating, writing, and managing temp‑table structures than executing user workload

dbo.cte_test – CTE workload behavior

The Processor Queue Length stays lower when using a CTE because SQL Server no longer wastes CPU cycles on temp‑table creation, metadata operations, and tempdb latch contention

The Batch Requests/sec graph stays noticeably lower with the CTE approach because each execution simply takes longer, reducing the number of batches SQL Server can complete per second.

We don’t see recompilations with the CTE approach because the plan is stable and reused, while temp tables force SQL Server to regenerate plans due to changing tempdb metadata and statistics. In other words, CTEs keep the optimizer calm, whereas temp tables constantly trigger new compilation cycles.

Tempdb shows no write activity with the CTE approach because hash worktables are kept entirely in memory as long as the memory grant is sufficient, so SQL Server never needs to spill them to disk.

CTE vs temp tables – Two strong approaches, one balanced perspective

When comparing CTEs and temp tables under real‑world load, the results show that both approaches shine in different dimensions. Temp tables often deliver faster single‑query execution thanks to accurate cardinality stable plans and less Memory Grants, yet they introduce significant overhead on shared resources such as CPU, scheduler queues, recompilation frequency, and tempdb I/O.

CTEs, on the other hand, run slower per execution but keep the system far more stable: fewer recompilations, lower processor queue length, minimal tempdb pressure, and more predictable behavior under concurrency.

The key takeaway is that query runtime alone is not enough to declare a winner. Temp tables may appear faster in isolation, but their impact on the entire SQL Server instance can be substantial under load. CTEs may take longer, yet they preserve overall system health and throughput. Both techniques are powerful and valid. The right choice depends on whether you optimize for individual query speed or for the broader resource footprint across your workload.

Medhdi Ghapanvari has aptly described the pros and cons of both patterns in his blog post and addressed the issues within the proper context (a direct comparison). Under the given circumstances, the solution using a CTE stood no real chance. But as the saying goes, „All roads lead to Rome.“ Many thanks to Mehdi for the inspiring post; without it, this blog post would not have been written, and I would not have examined the side effects more closely.

Thank you for reading!