Ira SQL ProIra SQL Pro

GROUPING SETS

advancedaggregation
2 min read

What are GROUPING SETS?

GROUPING SETS lets you define multiple groupings in one query. Instead of running separate GROUP BY queries and combining them with UNION ALL, you specify all the groupings together.

Syntax

SELECT col1, col2, aggregate_function(col3)
FROM table_name
GROUP BY GROUPING SETS (
  (col1, col2),
  (col1),
  ()
);

When to Use

  • Generating reports with subtotals and grand totals
  • Combining multiple GROUP BY perspectives in one query
  • Replacing multiple UNION ALL queries for different aggregation levels

Key Points

  1. Multiple Groupings — Each set in GROUPING SETS defines a separate grouping.
  2. Empty Set () — Represents the grand total (no grouping).
  3. NULLs — Columns not in the current grouping set appear as NULL.
  4. GROUPING() — The GROUPING() function distinguishes between real NULLs and grouping-level NULLs.
  5. Performance — More efficient than UNION ALL of separate queries because the table is scanned once.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

GROUPING SETS Challenge

Write a query that solve this task: count students grouped by grade, and also a grand total.

Expected result

One row per grade with counts, plus one row with NULL grade showing the grand total.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What are GROUPING SETS?

Initializing database...Each run starts from fresh sample data.

More Examples

Multi-level grouping

Count enrollments by course, by student, and overall.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What is the difference between GROUPING SETS and CUBE?
CUBE generates all possible combinations of the listed columns. GROUPING SETS lets you pick exactly which combinations you want.
How do I tell if a NULL is from the data or from the grouping?
Use the GROUPING() function. It returns 1 for columns that are aggregated away (grouping NULLs) and 0 for real data NULLs.

Related Topics