Summarizing Data with ROLLUP and CUBE, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 11.2 Free with a free account

Summarizing Data with ROLLUP and CUBE

Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.2 · lesson 65 of 768 min · free with a free account

← UNION vs. JOIN: Understanding the DifferenceNext lesson: Advanced Data Manipulation Using Subqueries →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Add subtotals and grand totals with ROLLUP, CUBE and GROUPING SETS.

  • Explain how column order controls the subtotals that ROLLUP produces
  • Compare the grouping levels produced by ROLLUP, CUBE and GROUPING SETS
  • Rewrite summary levels with UNION ALL where native syntax is unavailable
  • Use the GROUPING function to separate summary rows from stored nulls

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (983 words). Read along, or search it.

Opening Scenario

Totals Added by Hand

Maya Rao, Lantern Books' owner, gets a sales report with every department and channel. She still has to add department totals by hand. Then someone requests channel totals too. Would changing one grouping clause supply both, or would that change which summaries appear? We'll use an illustrative report table, and build the levels explicitly. SQLite runs the equivalents; labeled server listings show the native shortcuts.

Sandbox Setup

Detail Rows by Category and Region

These four invented report rows describe books and supplies, sold through campus and web channels. They are illustrative summaries, separate from the canonical order records. Ordinary group by returns one row for each category and region pair. Here the report uses region as its channel field. The aggregate adds amounts within each pair. A subtotal combines detail groups at one broader level; a grand total combines every input row. Run the setup and detail query. Sorting by the grouping columns makes the displayed order deliberate, rather than an accidental server behavior. Four detail rows appear. Books total one hundred sixty across channels, and supplies total sixty, but those summary rows are not yet in this result.

ROLLUP

Subtotals Along a Column Hierarchy

Rollup follows a hierarchy. With category first and region second, it includes category-region detail, category subtotals, and the grand total. The rightmost column drops first. Reversing the column order produces region subtotals instead, so choose the hierarchy that matches the report's question. SQL Server puts rollup around the grouping list. MySQL writes with rollup after it; these listings are references, not commands for SQLite. A summary uses null placeholders for omitted dimensions. Those placeholders describe an aggregation level, which is different from a missing value in a stored sale.

SQLite Equivalent

Rebuilding ROLLUP With UNION ALL

SQLite has no native rollup, so we spell out its levels. The first branch makes detail rows, and the second makes category subtotals. The final branch omits grouping and computes the grand total. Our temporary labels say all, because this tiny dataset has no real category named all. Union all preserves every summary row. Union would add duplicate elimination, which is unnecessary and can hide distinct levels if their visible values happen to agree. Run this equivalent. Its three branches express the same grouping levels as category-first rollup for these non-null input values. Seven rows appear: four details, two category subtotals, and one grand total of two hundred twenty. Grouping counts and result-row counts are different quantities.

Quick Check

Route Subtotals for Shipment Weights

A different report summarizes shipment weights by route. Two packages use the east route, and one uses the west route. What total will the east route receive? Choose nine, four, or seven units. Pause, and predict from these new inputs. Seven units belong to the east route. Its two packages weigh two and five, and the grouping combines those weights. Run the new report query. It isolates route subtotals, which would form the intermediate level of a route-first rollup. East receives seven, and west receives four. Four belongs to the other route; nine would combine weights from different routes.

CUBE

Totals for Every Dimension Subset

Cube adds every subset of the grouping dimensions. For category and region, that means details, category totals, region totals, and the grand total. Rollup skipped region-only totals in the original hierarchy. Cube includes them, rather than following just one path from detailed to broad. With two simple dimensions, cube names four grouping sets. Our four observed pairs produce nine output rows, because some sets produce several groups. For three dimensions, cube has eight grouping sets, while rollup has four. For five, the counts become thirty-two and six; request only useful summaries.

Native Syntax

Reading the GROUPING SETS Lists

Here is the native grouping sets spelling. Each parenthesized list names one grouping level, and the empty list would request a grand total. These two lists request category totals and region totals only. This is a selection of levels, rather than a hierarchy or every possible combination.

GROUPING SETS

Category and Region Totals Only

Grouping sets lets SQL Server list exactly the desired levels. For category totals and region totals only, name those two single-column sets. MySQL lacks native cube and grouping sets. Use separate grouped branches with union all, aligned into matching output columns. This executable version omits detail and grand-total branches. Choosing levels explicitly prevents a large report from burying the comparisons Maya actually requested. Run the selected-level equivalent. It also shows what each grouping set contributes, before we use native syntax. Four summary rows remain. Native grouping may share work, but neither the number of table scans nor the faster query is guaranteed; inspect execution plans.

GROUPING Function

Summary Nulls Versus Stored Nulls

A stored null region and a rolled-up null region can look identical. Coalesce alone cannot tell which meaning belongs to a row. Grouping returns one when the dimension is omitted by aggregation, and zero when it is retained. A retained null is still zero. Case uses that flag to print all channels for a subtotal. Without the having filter, the same case could label a stored missing channel as unknown, without confusing the two. Having grouping region equal to one retains category subtotals and the grand total for this hierarchy. Detail rows, including stored-null detail groups, are excluded.

Final Check

Totaling Only Missing-Channel Details

A new export has two missing-channel detail groups, worth fifteen and five. It also includes an all-channel summary worth fifty. The query totals only detail entries. What amount describes the missing-channel data? Pause, and calculate before running it. Twenty units describe the missing-channel data. Add fifteen and five, while excluding the summary row from the sum. Run the miniature export query. The level tag identifies which entries belong in this missing-data calculation. The result is twenty. Fifty is the broader summary, and seventy would double-count its relationship with the missing-channel detail entries.

Key Takeaways

Hierarchy, Every Subset or Chosen Levels

Maya can now request a hierarchy with rollup, or every dimension subset with cube. Column order determines rollup's intermediate totals. Grouping sets selects only the levels the report needs. MySQL and SQLite equivalents stack explicit grouped queries when the native form is unavailable. Label levels with grouping flags or explicit tags. Missing data and summary placeholders may look alike, but they answer different questions.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Summarizing Data with ROLLUP and CUBE

What does GROUP BY ROLLUP do in SQL?
ROLLUP adds subtotal rows and a grand total to a grouped result, treating the column list as a hierarchy. GROUP BY ROLLUP(category, region) returns category-region totals, a subtotal for each category and one grand total. The rightmost column is rolled up first, so reversing the columns gives region subtotals instead. SQL Server writes GROUP BY ROLLUP(category, region), while MySQL writes GROUP BY category, region WITH ROLLUP. Summary rows show NULL in the rolled-up columns.
What is the difference between ROLLUP and CUBE?
ROLLUP follows one hierarchy, while CUBE produces totals for every combination of the grouping columns. With category and region, ROLLUP gives details, category totals and a grand total, and CUBE adds region totals as well. The number of grouping sets grows quickly: n columns give n + 1 sets with ROLLUP but 2 to the power n with CUBE, so three columns mean 4 versus 8. MySQL supports WITH ROLLUP but not CUBE.
How do you tell a ROLLUP subtotal row from a real NULL value?
Use the GROUPING function, which returns 1 when a column was rolled up into a summary row and 0 when the row keeps that column, even if its stored value is NULL. For example, CASE WHEN GROUPING(region) = 1 THEN 'All channels' ELSE region END labels subtotal rows clearly. COALESCE alone cannot make this distinction, because it treats a summary placeholder and a missing stored value the same way.
What is GROUPING SETS used for?
GROUPING SETS lists exactly which grouping levels a query returns. GROUP BY GROUPING SETS ((category), (region)) gives category totals and region totals with no detail rows or grand total, and adding an empty set () would add the grand total. SQL Server supports it natively, but MySQL and SQLite do not, so there you write one grouped SELECT per level and combine them with UNION ALL, giving every branch the same output columns.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →