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

  1. Identify the exact query causing the error:
    1. Open SSMS and navigate to Query Explorer to find the most recent failed script.
    2. 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."
    3. Look for the line number and error context (e.g., "Dynamic SQL generation failed").
  2. Check for dynamic SQL mismatches:
    1. 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.
    2. 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: Add WITH (NOLOCK) or adjust the input.
    3. Use PRINT before your dynamic query to verify the exact SQL being executed.
  3. Validate CTE or subquery row counts:
    1. If the error comes from a CTE (e.g., WITH CTE AS (SELECT ...)), run SELECT COUNT(*) FROM CTE to confirm the expected row count matches your logic.
    2. 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.
  4. Inspect the PIVOT operation:
    1. If you’re using PIVOT (e.g., PIVOT (SUM([Value]) FOR [Category] IN ([A], [B]))), run SELECT DISTINCT [Category] FROM YourTable to verify all possible categories exist in the data. Missing columns in the input will cause the error.
    2. 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.
  5. Fix the dynamic list discrepancy:
    1. For parameter-driven queries, compare the @List or @Columns parameter 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.
    2. Use STRING_AGG (SQL Server 2017+) to inspect dynamic columns: SELECT STRING_AGG(ColumnName, ', ') AS ExpectedColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE TableName = 'YourTable';
  6. Apply a structural fix:
    1. 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.
    2. For pivots, pre-filter the data to include only valid categories: SELECT Category FROM YourTable WHERE Category IN ('A', 'B');
    3. Add OPTION (RECOMPILE) to the query if dynamic SQL is causing recompilation issues.

Common Mistakes

  • Ignoring NULL values: If a computed column requires non-NULL input but the table contains NULLs, the error occurs. Solution: Use COALESCE or 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 BY with a column that doesn’t exist in the query or has fewer distinct values than assumed. Test with GROUP BY first 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 @sql with @sql containing a static string to avoid dynamic SQL pitfalls entirely.
  • For complex queries, wrap the problematic section in a BEGIN TRY...END TRY block to capture the exact error context.
  • Use TOP 1 or FETCH FIRST 1 ROWS ONLY in 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

  1. It didn’t work after fixing the count:
    1. Re-run the PRINT step to confirm the query text is correct—copy and paste the output into a new query window for testing.
    2. Check for silent errors in the output data (e.g., missing columns, empty cells) that might mask the real issue. Use SELECT * with OPTION (FAST n) (where n is your expected row count) to see if it resolves the "compute mismatch."
    3. If using dynamic SQL, add SET SHOWPLAN_TEXT ON to inspect the execution plan for hidden issues.
  2. Error persists after replacing dynamic SQL:
    1. 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.
    2. 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.
  3. The issue appears in a scheduled job:
    1. Review the job’s TASK_NAME properties in SQL Server Agent to ensure the query is rerunning with identical parameters. Add SET LANGUAGE EN to the job’s script to avoid locale-related issues.
    2. Use OPTION (OPTIMIZE FOR UNKNOWN) in the query to account for varying data volumes in production.

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.