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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Advanced Data Manipulation Using Subqueries →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between ROLLUP and CUBE?
How do you tell a ROLLUP subtotal row from a real NULL value?
What is GROUPING SETS used for?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →