🗄️ SQL Server: Fix a Table Variable Breaking a Parallel Query Plan
A table variable carries no column-level statistics for the optimizer to use at all, unlike a temp table – SQL Server always falls back to a generic, far less accurate row-count assumption for a table variable regardless of how many rows it actually holds at execution time. Since parallelism is a cost-based decision driven heavily by each operator’s estimated row count, a badly underestimated table variable can convince the optimizer a plan is cheap enough to run serially even while it’s actually processing hundreds of thousands of real rows, producing a slow single-threaded plan for work that would otherwise easily qualify for, and benefit from, a parallel one.
🔎 The Problem
DECLARE @OrderIds TABLE (Id INT PRIMARY KEY); INSERT INTO @OrderIds SELECT Id FROM Orders WHERE Status = 'Pending'; -- @OrderIds now holds 300,000 rows SELECT o.* FROM Orders o JOIN @OrderIds t ON o.Id = t.Id; -- Execution plan: SERIAL, single thread -- Estimated rows at the table variable scan: 1 -- Actual rows at the table variable scan: 300,000
✅ The Fix
- Switch the table variable to a temp table (#OrderIds) whenever the row count is expected to be nontrivial, so the optimizer can gather and use real statistics on it instead of falling back to its generic fixed assumption.
- If a table variable needs to be kept for a specific reason (its transaction-scope behavior, or avoiding recompiles in a frequently-called routine), add OPTION (RECOMPILE) to the query using it, letting the optimizer size the plan against the variable’s actual runtime row count instead of the compile-time guess.
- When a query involving a table variable runs slower than expected, check the actual execution plan’s estimated-vs-actual row counts at that specific operator first, before investigating indexes or hardware – this exact mismatch is the first thing worth ruling out.
🚨 Why This Is Dangerous
Because the query still returns completely correct results, a performance regression caused purely by table-variable cardinality estimation can go undiagnosed for a long time, with the slowdown blamed on ‘the server getting busier’ or ‘the data growing’ rather than a specific, fixable optimizer behavior.
SQL Server doesn’t guess how many rows are in your table variable – it assumes, and that assumption doesn’t get more accurate just because your data did.



