A CTE, a temp table, and a table variable can all make a SQL Server query easier to write, but they solve different problems. A CTE names a query expression for one statement. A temp table stores rows so later statements can reuse them, with support for indexes and column statistics. A table variable also stores rows, but its scope is narrower and SQL Server has less information about the distribution of its values.
Start with scope, not an arbitrary row-count cutoff. If you only need to break one statement into readable steps, start with a CTE. If several statements need the same result or you want an index on an intermediate set, consider a local temp table. If the data belongs to one batch or stored procedure and the queries against it are straightforward, a table variable may be a good fit. When more than one option works, compare them with representative data.
CTE vs Temp Table vs Table Variable: The Key Differences
- CTE: A named query expression, introduced with WITH, that is available to one following statement. It does not create a separately stored result that you can index or query in another statement.
- Local temp table: A temporary table named with a single #, such as #CustomerTotals. It stores rows, supports indexes and statistics, and can be queried in multiple statements within its scope.
- Table variable: A variable declared with a table definition, such as @CustomerTotals. It stores rows for use within its declaring batch or routine. It supports keys and certain indexes declared with the table, but not column distribution statistics.
The most important distinction is whether you are naming a query or storing its output. A CTE leaves its definition in the same statement as the query that uses it. A temp table or table variable separates the population step from later reads. That boundary can prevent repeated work and give you control over the intermediate data, but writing and reading those rows has a cost.
Also distinguish row count from value distribution. Knowing a table contains 10,000 rows does not tell SQL Server how many match a particular customer or date. That difference matters when comparing temp table statistics with table variable deferred compilation.
What Is a CTE in SQL Server?

A common table expression gives an intermediate query a name. Define it before a statement, then refer to it in that statement much as you would refer to a derived table. You can define multiple CTEs in one WITH clause, and a later definition can reference an earlier one. This makes it practical to separate filtering, aggregation, ranking, and final selection without creating objects for every step.
Example: Aggregate and Filter in One Statement
Assume dbo.Orders has a non-null integer CustomerID, an OrderDate, and a non-null TotalAmount defined as decimal(19,2). This example totals orders from January 1, 2026 onward, then returns customers whose totals meet a threshold.
;WITH CustomerTotals AS (SELECT CustomerID, SUM(TotalAmount) AS TotalSpend FROM dbo.Orders WHERE OrderDate >= '20260101' GROUP BY CustomerID) SELECT CustomerID, TotalSpend FROM CustomerTotals WHERE TotalSpend >= 1000 ORDER BY TotalSpend DESC, CustomerID;
The semicolon before WITH ensures that a preceding statement, if there is one, is terminated. The CTE name is available to that SELECT only. A second SELECT cannot refer to CustomerTotals unless you define it again or store its rows somewhere.
Does a CTE Store or Reuse Its Results?
A CTE is not a materialized result you can count on SQL Server to compute once. The optimizer considers its definition together with the rest of the statement. Depending on the query, this can let SQL Server apply filters early or choose join orders across what looks in the text like a series of steps. The syntax does not force those steps to run in the order you wrote them.
Referencing the same CTE twice also does not guarantee that its underlying work happens only once. SQL Server may repeat work or choose a spool to retain intermediate rows within the plan. Inspect the actual execution plan before assuming either outcome. If an expensive aggregation or join really is repeated, testing a temp table is worthwhile. If the outer query only needs a small fraction of the source rows, keeping the work in one statement may be better than storing the entire intermediate result.
When a CTE Is the Natural Choice
- Use it to organize one statement, such as ranking orders per customer and then filtering by rank.
- Use it when you want SQL Server to optimize the underlying query and its consumer together.
- Use a recursive CTE for a hierarchy or similar traversal when the problem fits that pattern. Verify the stopping condition and remember that SQL Server defaults to a recursion limit of 100 unless you specify a different MAXRECURSION setting on the outer statement.
What Is a Temp Table in SQL Server?

A temporary table holds rows in tempdb. Create a local temp table with CREATE TABLE #Name, or create and populate it from a query with SELECT INTO #Name. An explicit definition is useful when you want to control data types, nullability, and keys. SELECT INTO is convenient for staging a query result, but check that the inferred column definitions fit the statements that will consume it.
Example: Store Totals for Multiple Statements
This version computes the customer totals once and stores them. One statement returns the high-spend customers; a second counts every customer in the staged set without aggregating dbo.Orders again.
CREATE TABLE #CustomerTotals (CustomerID int NOT NULL PRIMARY KEY, TotalSpend decimal(38,2) NOT NULL);
INSERT INTO #CustomerTotals (CustomerID, TotalSpend) SELECT CustomerID, SUM(TotalAmount) FROM dbo.Orders WHERE OrderDate >= '20260101' GROUP BY CustomerID;
SELECT CustomerID, TotalSpend FROM #CustomerTotals WHERE TotalSpend >= 1000 ORDER BY TotalSpend DESC, CustomerID;
SELECT COUNT_BIG(*) AS CustomerCount FROM #CustomerTotals;
DROP TABLE #CustomerTotals;
The total uses decimal(38,2) because SQL Server returns that type when SUM aggregates the example’s decimal(19,2) column. More importantly, both reads operate on the same staged rows. If source orders change between the two reads, neither read recomputes its results from the source. That reuse is useful in reports, but it does not replace transaction isolation when the population step itself needs a particular consistency guarantee.
Why Statistics and Indexes Matter
SQL Server can create and maintain statistics on temp table columns. Statistics help it estimate how many rows a filter or join will return. Those estimates can affect join strategy, join order, and the memory reserved for sorts and hashes. Splitting a query into stages can help when estimates for a complex intermediate result are poor and those errors affect the rest of the plan. Temp table statistics can improve those estimates; they do not guarantee a better plan.
You can also add an index after creating a temp table. The example’s primary key supports access by CustomerID. It does not directly support the filter and sort by TotalSpend. If a workload repeatedly reads narrow spend ranges, an index with TotalSpend as its leading key is worth testing. For one scan of a modest result, the index build may cost more than it saves. Measure index creation and population as well as the reads.
Scope and Cleanup
A local temp table created outside a stored procedure normally remains available for the session unless it is dropped. It can survive a batch separator in a client tool when the connection stays the same. A local temp table created inside a stored procedure is automatically dropped when that procedure finishes. Nested procedures can access a temp table created by their caller while it is in scope.
Dynamic SQL adds a scope boundary. A dynamic batch can generally use a local temp table already created by its caller on the same connection. A local temp table created inside that dynamic batch, however, is not available to the caller after the dynamic batch ends. If both sides need the table, create it in the outer scope and populate it inside the dynamic batch.
Global temp tables use ## and can be visible across sessions. They are not a drop-in fix for a local scope problem: shared visibility changes who can access the data and introduces naming and lifetime concerns. For intermediates that belong to one session, use a local temp table.
What Is a Table Variable in SQL Server?

A table variable is declared with DECLARE @Name TABLE. It can hold rows across multiple statements in the same batch, stored procedure, or function that declares it. A batch separator ends access to a variable declared in the preceding batch. A separate dynamic SQL batch also cannot directly reference an ordinary table variable declared by its caller.
Despite the name, an ordinary table variable is not an in-memory-only alternative to a temp table. It uses tempdb, and its pages can be cached in memory, as temp table pages can. A CTE avoids creating either object, but a plan using a CTE can still use tempdb for internal work such as spooling or spills. Choose based on the workload, not on the assumption that one syntax guarantees memory-only execution.
Example: Keep a Working Set in One Batch
This version produces the same two outputs as the temp table example. Run the declaration and subsequent statements together as one batch. There is no separate drop statement because the variable goes out of scope automatically.
DECLARE @CustomerTotals TABLE (CustomerID int NOT NULL PRIMARY KEY, TotalSpend decimal(38,2) NOT NULL);
INSERT INTO @CustomerTotals (CustomerID, TotalSpend) SELECT CustomerID, SUM(TotalAmount) FROM dbo.Orders WHERE OrderDate >= '20260101' GROUP BY CustomerID;
SELECT CustomerID, TotalSpend FROM @CustomerTotals WHERE TotalSpend >= 1000 ORDER BY TotalSpend DESC, CustomerID;
SELECT COUNT_BIG(*) AS CustomerCount FROM @CustomerTotals;
The primary key gives SQL Server an index on CustomerID and enforces uniqueness. It does not give the variable a statistics histogram on TotalSpend. While a table variable can have keys and supported inline indexes, you cannot treat it like a temp table and use a standalone CREATE INDEX statement on it later.
How Deferred Compilation Changes Estimates
Historically, statements reading table variables often got a one-row estimate, even when the variables held far more rows. That mismatch could lead SQL Server to choose a plan that worked for a few rows but performed poorly for a larger set. SQL Server 2019 introduced table variable deferred compilation for eligible statements at database compatibility level 150 or higher, when the feature is enabled.
Deferred compilation lets SQL Server wait until a statement first executes before compiling it, so the optimizer can use the table variable’s actual row count at that point. It does not add column distribution statistics, and a cached plan can reuse the initial estimate on later executions. If one run loads a handful of customers and the next loads thousands, the plan compiled for the first run may not fit the next. Likewise, knowing the overall row count still does not tell SQL Server what fraction of customers meet the spend threshold.
That is why there is no reliable rule such as “use a table variable under 100 rows.” A larger set read once in a simple scan may work well. A smaller set that drives a selective join into a large table can still benefit from better estimates or a different index. Check both the database compatibility level and the actual plan before relying on behavior associated with a particular SQL Server release.
How to Choose for a Real Query
Start With the Number of Consumers
If one statement needs an intermediate result once, a CTE is a good default for readability. If multiple statements need identical rows, use a stored intermediate rather than redefining the query in every statement. A temp table is a sensible starting point when the consumers perform different joins, filters, or aggregations. A table variable is a reasonable candidate when the consumers stay local and mostly scan the rows or look them up by a declared key.
Decide Whether Staging Helps the Optimizer
Suppose a report identifies active customers from recent orders and then joins those customers to a large transaction history. With a CTE, SQL Server optimizes the filtering and joining as part of one statement. That can work well, particularly if a downstream predicate lets the optimizer avoid processing much of the source. If the actual plan badly misjudges the number of active customers and chooses an inefficient join, populating a temp table first gives the downstream statement a separate optimization opportunity and access to statistics on the staged columns.
Staging can also hurt. If you load every active customer into a temp table but the final statement reads only one region, you may write thousands of rows the final query never needs. An equivalent single statement might let SQL Server apply the region filter earlier. If you do stage the data, see whether you can move the filter into the population query without changing the result.
Check Scope Before Tuning Performance
A second statement cannot use a CTE, however fast the first statement runs. A nested procedure cannot directly read an ordinary table variable declared by its caller. If those boundaries conflict with the design, choose a different construct before benchmarking. If you need a temporary object that both a stored procedure and its nested routines can read, a caller-created local temp table is a practical option.
Mix Approaches When Each Has a Clear Job
You do not have to pick one construct for an entire procedure. A CTE can organize a multi-step transformation in the statement that inserts into a temp table. Later statements can then read the staged rows without recalculating the transformation. This gives you readable query logic and an explicit reuse boundary. Add the boundary where it saves work or improves plan quality, not after every step.
How to Compare Performance Fairly
Benchmark versions that return the same rows and use equivalent filters, joins, and output ordering. In the examples above, the CTE returns only the high-spend customer list, while the stored versions also count the staged customers. Compare the list-only implementations for a one-output test. For a two-output test, make each implementation produce both results and include the cost of any repeated aggregation.
- Choose realistic parameter values. Try a narrow date range and a broad one. If the workload is skewed, test common and uncommon values rather than only an average case.
- Measure the whole operation. Use SET STATISTICS IO ON and SET STATISTICS TIME ON to compare logical reads, CPU time, and elapsed time. For staged designs, count the load and index-building work as well as the final statements.
- Review actual execution plans. Compare estimated and actual rows at key joins and filters. Look for repeated source access, large estimate errors, unexpected scans, or spills. A scan is not automatically a problem; it may be the right choice when most rows qualify.
- Repeat the tests in different orders. Data caching and plan reuse can change results. Test a small first execution followed by a large one, and then reverse the order in a controlled environment. Do not clear shared production caches to make a benchmark easier to interpret.
- Check concurrency when it matters. A design that wins in a single session can behave differently when many sessions create and populate temporary objects. If the procedure runs frequently, test under a representative load and watch for extra tempdb activity.
Pick the simplest implementation that meets your scope and performance requirements. A CTE is for expressing logic within one statement. A temp table is for storing a reusable result when indexing, statistics, or a separate optimization step can help. A table variable is for a local working set when its narrower scope and lack of column statistics do not get in the way.