How to fix Error 8160 on Windows Server 2025 / Windows 11

Troubleshooting Guide: Error 8160 – GROUPING or GROUPING_ID Function Without GROUP BY Clause

Why This Error Happens

This error occurs when a T-SQL query references the GROUPING or GROUPING_ID function in the SELECT list, HAVING clause, or ORDER BY clause, but the query itself lacks a corresponding GROUP BY clause. SQL Server 2025’s query optimizer requires these functions to operate strictly within an aggregation context, since they are designed to identify whether a given column in a result set is an aggregated summary row (typically from ROLLUP, CUBE, or GROUPING SETS). Without a GROUP BY clause present, the parser has no aggregation context to evaluate, causing the batch to fail compilation immediately.

Step-by-Step Resolution Guide

Step 1: Review the Query Structure

  • Open the failing query in SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Locate every instance of GROUPING(column_name) or GROUPING_ID(column_name, ...) in your SELECT, HAVING, or ORDER BY clauses.
  • Confirm whether a GROUP BY clause exists anywhere in the same query scope.

Step 2: Add or Correct the GROUP BY Clause

  • If you intended to summarize data, append a GROUP BY clause using ROLLUP, CUBE, or GROUPING SETS to match your reporting needs.
  • Example fix:
  SELECT Department, GROUPING(Department) AS IsAggregated, SUM(Salary)
  FROM Employees
  GROUP BY ROLLUP(Department);
  • Ensure the column referenced inside GROUPING() or GROUPING_ID() is also listed in the GROUP BY clause.

Step 3: Remove Unnecessary Grouping Functions

  • If the query was never meant to produce subtotal/grand-total rows, simply remove the GROUPING or GROUPING_ID function calls entirely.
  • Replace them with standard aggregate functions (SUM, COUNT, AVG) if summary statistics are still required without the rollup indicator flag.

Step 4: Check Dynamic SQL and Stored Procedures

  • If the query is generated dynamically (via sp_executesql or string concatenation), inspect the application or ETL logic (e.g., SSIS packages, Power BI DirectQuery) that builds the SQL string.
  • Verify no conditional logic is stripping the GROUP BY clause while leaving the GROUPING function intact.

Step 5: Recompile and Test the Corrected Batch

  • Save the corrected script and execute it in isolation using SET SHOWPLAN_TEXT ON to validate the execution plan compiles without errors.
  • Clear the plan cache for the specific query if testing in a development environment: DBCC FREEPROCCACHE.

Alternative or Verification Steps

  • Run the corrected query against a test table with sample NULL values to confirm the GROUPING() function correctly returns 1 for superaggregate rows and 0 for detail rows.
  • If using an ORM or BI tool (e.g., SSRS, Power BI) that auto-generates T-SQL, update the report’s dataset query manually, as the error often stems from auto-generated rollup logic that omits the necessary GROUP BY syntax.