SQL GROUPING function
Returns 1 when the column is a rolled-up placeholder NULL, 0 when it is a real value.
- Catégorie
- Aggregates
- Returns
integer- In this category
- 36 of 52
Syntaxe
GROUPING(col) | GROUPING(col1, col2)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | Supported under this name. |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Oui | MySQL 8.0+, with WITH ROLLUP only |
| SQLite | Not built in | no ROLLUP, so nothing to flag |
| Oracle | Oui | one argument; GROUPING_ID for several |
Exemples
PostgreSQL
SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY ROLLUP(make);
SQL Server
SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY make WITH ROLLUP;
Bon à savoir
- Without ROLLUP, CUBE or GROUPING SETS in the query, GROUPING is always 0.
- PostgreSQL and MySQL accept several columns and return a bitmask (rightmost argument = lowest bit); SQL Server and Oracle take exactly one and offer GROUPING_ID for the bitmask.
- It is the only reliable way to tell a real NULL value from the NULL that ROLLUP prints on subtotal rows.
Questions about GROUPING
What do 0 and 1 mean?
0 = the column holds a real value; 1 = the row is a super-aggregate and the column shows a placeholder NULL.
Can I filter subtotal rows?
Yes: HAVING GROUPING(make) = 1 keeps only the rolled-up rows; = 0 keeps only detail rows.
Does it work without ROLLUP?
It runs, but every row returns 0.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Cross-tab with row and column totals Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, 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.