You’re encountering SQL Server Error 163 when a computed column, aggregate function, or dynamic SQL operation fails because the number of rows in your input list doesn’t match the expected result set. This often happens in scripts that join tables, apply window functions, or use CTEs (Common Table Expressions) without proper validation. The error prevents execution until the mismatch is corrected—no data will be returned until the issue is resolved. For example, a query building a pivot table with a dynamic column list where the source data has fewer rows than specified will trigger this error.
What You’ll Need
- A working SQL Server instance (2016 or later; earlier versions may have slightly different error messages)
- SSMS (SQL Server Management Studio) or a compatible IDE (Visual Studio, Azure Data Studio)
- Access to the database containing the problematic query
- Basic understanding of SQL syntax for your specific use case (CTEs, joins, dynamic SQL)
Step-by-Step Troubleshooting
- Identify the exact query causing the error:
- Open SSMS and navigate to Query Explorer to find the most recent failed script.
- Check the error details in the Messages tab—SQL Server 2016+ will show "Error 163" with a descriptive message like "Compute By List does not match."
- Look for the line number and error context (e.g., "Dynamic SQL generation failed").
- Check for dynamic SQL mismatches:
- If the error occurs in a script that builds SQL dynamically (e.g., for parameterized pivots), inspect the generated query. The error usually appears when the row count in the input list (FROM clause) doesn’t match the output columns created.
- Example of the problem: A query like
SELECT * INTO #Temp FROM (VALUES ('A'), ('B')) AS T(x)with 3 columns will fail because only 1 row is generated. Fix: AddWITH (NOLOCK)or adjust the input. - Use
PRINTbefore your dynamic query to verify the exact SQL being executed.
- Validate CTE or subquery row counts:
- If the error comes from a CTE (e.g.,
WITH CTE AS (SELECT ...)), runSELECT COUNT(*) FROM CTEto confirm the expected row count matches your logic. - For window functions like
ROW_NUMBER() OVER (PARTITION BY ...), ensure the PARTITION clause divides the data logically. A mismatch can occur if the expected partitions don’t align with actual rows.
- If the error comes from a CTE (e.g.,
- Inspect the PIVOT operation:
- If you’re using PIVOT (e.g.,
PIVOT (SUM([Value]) FOR [Category] IN ([A], [B]))), runSELECT DISTINCT [Category] FROM YourTableto verify all possible categories exist in the data. Missing columns in the input will cause the error. - Check the source table’s data for NULLs or NULL-equivalent values (e.g., empty strings or default values) that might be excluded from aggregation.
- If you’re using PIVOT (e.g.,
- Fix the dynamic list discrepancy:
- For parameter-driven queries, compare the
@Listor@Columnsparameter count with the actual data. For example:DECLARE @Columns NVARCHAR(MAX) = 'A,B,C';If the data only has columns A and B, the error will occur when trying to process C. - Use
STRING_AGG(SQL Server 2017+) to inspect dynamic columns:SELECT STRING_AGG(ColumnName, ', ') AS ExpectedColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE TableName = 'YourTable';
- For parameter-driven queries, compare the
- Apply a structural fix:
- If using a CTE with a known row count, replace dynamic generation with a static query:
SELECT * FROM (VALUES ('A'), ('B')) AS T(x)instead of generating rows at runtime. - For pivots, pre-filter the data to include only valid categories:
SELECT Category FROM YourTable WHERE Category IN ('A', 'B'); - Add
OPTION (RECOMPILE)to the query if dynamic SQL is causing recompilation issues.
- If using a CTE with a known row count, replace dynamic generation with a static query:
Common Mistakes
- Ignoring NULL values: If a computed column requires non-NULL input but the table contains NULLs, the error occurs. Solution: Use
COALESCEor filter out NULLs before aggregation. - Dynamic SQL without validation: Generating SQL at runtime without checking the input data’s alignment (e.g., column count vs. target rows) leads to mismatches. Always inspect the generated query first.
- Incorrect window function partitioning: Using
PARTITION BYwith a column that doesn’t exist in the query or has fewer distinct values than assumed. Test withGROUP BYfirst to validate partitions. - Overlooking data types: Mixing numeric and string columns in a single computed result set. Ensure all target columns in the computed list have compatible types.
Tips
- Use
EXEC sp_executesql @sqlwith@sqlcontaining a static string to avoid dynamic SQL pitfalls entirely. - For complex queries, wrap the problematic section in a
BEGIN TRY...END TRYblock to capture the exact error context. - Use
TOP 1orFETCH FIRST 1 ROWS ONLYin debug queries to isolate row-level issues quickly. - If using Power Query or SSIS, check the "Data Validation" step—these tools often generate dynamic SQL with mismatched row counts.
Troubleshooting
- It didn’t work after fixing the count:
- Re-run the
PRINTstep to confirm the query text is correct—copy and paste the output into a new query window for testing. - Check for silent errors in the output data (e.g., missing columns, empty cells) that might mask the real issue. Use
SELECT *withOPTION (FAST n)(where n is your expected row count) to see if it resolves the "compute mismatch." - If using dynamic SQL, add
SET SHOWPLAN_TEXT ONto inspect the execution plan for hidden issues.
- Re-run the
- Error persists after replacing dynamic SQL:
- Compare the static query’s output with the original dynamic query’s expected result. Use
SELECT * FROM YourTable WHERE [Condition]to verify the data alignment. - Check for stored procedures or functions that might be modifying the data between the original query and the fix—trace the query’s execution path.
- Compare the static query’s output with the original dynamic query’s expected result. Use
- The issue appears in a scheduled job:
- Review the job’s
TASK_NAMEproperties in SQL Server Agent to ensure the query is rerunning with identical parameters. AddSET LANGUAGE ENto the job’s script to avoid locale-related issues. - Use
OPTION (OPTIMIZE FOR UNKNOWN)in the query to account for varying data volumes in production.
- Review the job’s
Frequently Asked Questions
Why does SQL Server error 163 only happen in dynamic SQL?
Dynamic SQL generates new SQL code at runtime, so the compiler doesn’t know the exact row count or column list until execution. Static queries are compiled once with known structures, while dynamic queries rely on input parameters that may not match the target schema.
How can I test a dynamic pivot query before running it?
Use a parameterized approach: wrap the pivot logic in a function like this:
CREATE FUNCTION dbo.TestPivot(@Categories NVARCHAR(MAX))
RETURNS TABLE AS
RETURN (SELECT * FROM YourTable WHERE Category IN (STRING_SPLIT(@Categories, ',')));
Then call it with each category group separately to validate the data.
Why does my CTE with a fixed number of rows fail in SQL Server?
If your CTE uses VALUES with more rows than expected (e.g., VALUES ('A'), ('B'), ('C') but the target join expects only 2 columns), SQL Server enforces strict type/column alignment. Use WITH (NOLOCK) or adjust the input rows.
Is there a way to force SQL Server to ignore compute mismatches?
No—error 163 is a design safety feature. Workarounds like OPTION (RECOMPILE) or OPTION (FAST n) can sometimes bypass it, but they’re not reliable and may hide real logical errors.
How do I debug a window function mismatch without rewriting the query?
Use OPTION (INITIALIZER) to show the function’s initialization context, then add OPTION (OPTIMIZE FOR UNKNOWN) to test with real data. Alternatively, reduce the window function’s partition columns to isolate the issue.
Will this error always appear in SSMS, or can it hide in other tools?
The error is visible in SSMS but may be masked in Power BI or Azure Synapse if the query engine treats it as a "runtime" issue. Always inspect the server-side execution in SSMS or Log Analytics for the full context.