GROUPING_ID()

GROUPING_ID is a function that computes the level of grouping, in a SELECT, HAVING, or ORDER BY clause.

Signature

GROUPING_ID ( <column_expression> [ , ...n ] )

Examples

SELECT region, GROUPING_ID(region) AS gid, SUM(amount) AS total FROM dbo.orders GROUP BY ROLLUP (region) ORDER BY gid, region;
region               gid         total
-------------------- ----------- ----------------------------------------
east                           0                                   453.00
north                          0                                   268.50
south                          0                                   126.75
NULL                           1                                   848.25

Run against SQL Server 16.0.4265.3 on 2026-09-13. This is the output we got, not the documentation’s.

Want to run this against your own SQL Server server from an iPhone, iPad or Mac? These are ours — every connection goes straight from the device to your database, with no account and no server of ours in between.

Signature and description adapted from the Microsoft SQL documentation, used under the CC BY 4.0. SQL Server and Azure are trademarks of the Microsoft group of companies. This page is not affiliated with Microsoft.