BBampaa

Lessons › SQL › Deep Dive: Advanced Window Functions

SQL lesson

GROUPING SETS

GROUPING SETS lets you define multiple grouping levels in a single query, so the database returns several different summaries all at once.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Creating Multiple Retail Subtotals with GROUPING SETS

SELECT category, region, SUM(revenue) AS total_revenue
FROM orders
GROUP BY GROUPING SETS ((category), (region), ())

Result:

categoryregiontotal_revenue
Electronics531.25
Clothing225.0
Home95.25
North555.75
South295.75
851.5

Step by step

  1. Run the query without SUM so you can see what the unfiltered values look like.
    SELECT category, region, revenue
    FROM orders
    GROUP BY GROUPING SETS ((category), (region), ());
  2. SUM totals the numbers in a column. Works on numeric columns only.
    SELECT category, region, SUM(revenue)
    FROM orders
    GROUP BY GROUPING SETS ((category), (region), ());
  3. AS gives the SUM result a friendly column name so the output reads cleanly.
    SELECT category, region, SUM(revenue) AS total_revenue
    FROM orders
    GROUP BY GROUPING SETS ((category), (region), ());

Practice

Try each one in your head first, then open the answer.

1. Using orders, write a query that returns counts grouped by order_id, customer_id, and the grand total - using GROUPING SETS.
SELECT order_id, customer_id, COUNT(*) FROM orders GROUP BY GROUPING SETS ((order_id), (customer_id), ())
2. Using store_sales, write a query that returns counts grouped by sale_id, store_id, and the grand total - using GROUPING SETS.
SELECT sale_id, store_id, COUNT(*) FROM store_sales GROUP BY GROUPING SETS ((sale_id), (store_id), ())
3. Using products, write a query that returns counts grouped by product_id, brand, and the grand total - using GROUPING SETS.
SELECT product_id, brand, COUNT(*) FROM products GROUP BY GROUPING SETS ((product_id), (brand), ())
4. Using reviews, write a query that returns counts grouped by review_id, product_id, and the grand total - using GROUPING SETS.
SELECT review_id, product_id, COUNT(*) FROM reviews GROUP BY GROUPING SETS ((review_id), (product_id), ())
5. Using employees, write a query that returns counts grouped by employee_id, full_name, and the grand total - using GROUPING SETS.
SELECT employee_id, full_name, COUNT(*) FROM employees GROUP BY GROUPING SETS ((employee_id), (full_name), ())

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed