SQL GROUPING_ID function
Packs the per-column GROUPING flags of a rollup row into a single integer.
- Category
- Aggregates
- Returns
integer- In this category
- 37 of 52
Syntax
GROUPING_ID(a, b) | GROUPING_ID(a, b, c)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Yes | Supported under this name. |
| PostgreSQL | Different name or syntax | no GROUPING_ID; GROUPING(a, b) with several arguments returns the same bitmask |
| MySQL | Not built in | no GROUPING_ID; GROUPING(a, b) with several arguments returns the same bitmask (8.0+) |
| SQLite | Different name or syntax | no ROLLUP or GROUPING SETS |
| Oracle | Yes | Supported under this name. |
Examples
SQL Server
SELECT make, model, GROUPING_ID(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);
Oracle
SELECT make, model, GROUPING_ID(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);
PostgreSQL
SELECT make, model, GROUPING(make, model) AS lvl, SUM(sales) FROM items_sold GROUP BY ROLLUP(make, model);
Good to know
- The last argument is the lowest bit: GROUPING_ID(a, b) = GROUPING(a) * 2 + GROUPING(b). On ROLLUP(a, b) that gives 0 for detail rows, 1 for per-a subtotals and 3 for the grand total.
- PostgreSQL and MySQL have no GROUPING_ID, but their GROUPING(a, b) accepts several arguments and returns the same number, so a port is a rename.
- Handy for a single CASE that labels each row as detail, subtotal or total, and for HAVING GROUPING_ID(a, b) = 0 to keep detail rows only.
Questions about GROUPING_ID
How is GROUPING_ID different from GROUPING?
GROUPING handles one flag per call; GROUPING_ID packs several columns into one integer you can compare or label with.
What is GROUPING_ID in PostgreSQL?
GROUPING(a, b) with several arguments. It uses the same bit order as SQL Server and Oracle, so the numbers match.
Does MySQL have GROUPING_ID?
No, but MySQL 8.0's GROUPING(a, b) takes several columns and returns the same bitmask.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.