UPI Study › Courses › Database Programming › Free lessons › Lesson 5.9 Free with a free account
Grouping Rows and Calculating Summaries with GROUP BY
Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.9 · lesson 34 of 769 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: Filtering Grouped Results and Advanced Aggregation with HAVING →← Conditional Logic in SQL: The CASE StatementNext lesson: Filtering Grouped Results and Advanced Aggregation with HAVING →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Summarizing rows with GROUP BY, COUNT, SUM, AVG, MIN, and MAX.
- Calculate whole-table and per-group summaries with aggregate functions
- Distinguish COUNT(*), COUNT(column), and COUNT(DISTINCT column)
- Explain how aggregates treat NULL values and how AVG return types differ by engine
- Select only grouped columns or aggregates so each result row matches its group
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 (1,054 words). Read along, or search it.
Opening Question
From One Row per Employee to Departments
Amina Diallo is preparing Lantern Books' staffing report. The owner wants department totals, but a query still returns one record for every employee. How does she change the unit of the answer, from individual people to one summary per department, without losing track of missing bonuses? An aggregate reduces many inputs to a summary value. Group by decides which records contribute to each summary, and the selected columns must fit that unit.
Definition
Aggregate Functions and Grouping Combinations
Our staff extension has eight illustrative records, assigned to departments and cities. Salary is recorded for everyone, while only some bonuses are present. An aggregate function reads multiple values. Count, sum, average, minimum, and maximum answer different questions about that collection. Without group by, an aggregate query summarizes the entire input. With group by, the same calculation runs separately for each distinct grouping combination. Grouping does not promise presentation order. We will request order by explicitly, so it is easy to compare the result with the intended groups.
Whole-Table Summary
Count, Sum, Average, Minimum, and Maximum
Count star counts input records. Sum adds their salaries, average divides the total by the count of present salaries, and minimum or maximum finds an extreme. These expressions return a single summary record, because there is no grouping key. The output no longer represents any one employee. Run the summary. All salaries are present in this dataset, so average uses every employee's salary. The result counts eight people and totals forty-one thousand five hundred. The mean is five thousand one hundred eighty-seven point five, between the minimum and maximum.
Dialect Trap
AVG Return Types Differ by Engine
Average has an important result-type difference. SQL Server averaging an integer salary returns an integer, so the fractional part of this mean is lost. Convert the input to an appropriate decimal type before averaging to preserve fractional detail there. Casting a truncated final mean afterward cannot restore information. MySQL returns a decimal for integer inputs, while SQLite average produces a floating result. The local output does not establish another engine's return type.
GROUP BY Basics
One Summary Row per Department
Group by department gathers equal department values into one logical bucket. Each count and sum now sees only the records belonging to that bucket. The department value identifies a result row; the aggregate columns summarize its members. You do not write a separate query for every department. Run the grouped report. An explicit final order makes the department labels predictable, without claiming that grouping itself sorts them. HR has two people, while IT and Sales have three each. The totals are separate department summaries, rather than repeated whole-company figures.
Multiple Keys
Department and City Combinations
Adding city changes the unit of the result. A group is now a distinct department-and-city combination, rather than a department alone. Only combinations that occur in the input become groups. Listing two keys does not manufacture every possible city for every department. Run the two-key summary. Compare the number of output rows with the distinct combinations in the source records. Six combinations produce six result rows. A department split across cities now contributes multiple summaries, each with its own salary total.
Counting Variants
Counting Rows, Present Values, and Distinct Cities
Count star and count column do different work. Count star includes every record, while count bonus includes only records with a present bonus. A recorded zero would count as present. Count distinct city instead removes repeated present cities before counting, so it measures different locations. Run all three counts together. Their differences are intentional, because their units are employees, recorded bonuses, and distinct cities. HR has staff but no recorded bonuses. IT and Sales each have fewer recorded bonuses than people, so those counts cannot be substituted for headcount.
NULL Handling
Aggregates Ignore Missing Bonuses
Except for row counting, these aggregates normally ignore missing inputs. The average bonus uses recorded bonus amounts, rather than assuming missing amounts are zero. If every bonus in a selected collection is null, there are no present values to total, average, minimize, or maximize. Those aggregates return null. Run the all-missing department example. Count bonus can still answer its own question, because it counts how many nonnull values it found. Count is zero, and the other bonus summaries are null. That combination says no amounts were recorded; it does not establish a zero bonus budget.
Common Mistake
Ungrouped Columns in a Grouped Query
A grouped result has one row per group. Selecting an ungrouped employee name asks for a value that may differ among the group's members. SQL Server refuses this query. MySQL's default only full group by mode also refuses ambiguous selected columns, although it recognizes some functional dependencies. SQLite allows bare columns in aggregate queries, which can hide the mistake. Acceptance does not make an arbitrary selected name a meaningful department representative. The portable habit is to group each varying selected column or aggregate it. Adding a name to group by changes the groups; minimum name means the smallest name. Those repairs answer different questions. Choose the unit deliberately, rather than wrapping a troublesome column in an aggregate just to silence a complaint.
WHERE Before Grouping
Filtering Contributors Before Groups Form
Where filters input records before groups are formed. It can restrict the report to a city, or keep only salaries meeting an individual threshold. A condition on a group count cannot run there, because the count does not yet exist. Group conditions belong in having, after aggregation. Keep those two questions distinct: which records contribute, and which completed summaries should remain? Changing the contributors changes the summaries themselves.
Quick Check
Row Count Versus Score Count
A new score relation includes missing values and a recorded zero. This query first selects team one, then computes the two forms of count. Which pair is returned, row count first and score count second? Decide how each count treats the zero and the missing score. Pause, and decide.
Answer
Two Records but One Recorded Score
The answer is two and one. Team one contributes two records, but only its recorded zero is a nonnull score. One and one incorrectly drops the missing-score record from count star. Two and two incorrectly treats the missing marker as a recorded score. The run confirms both units. Count star describes records, while count score describes the presence of score values within those records.
Key Takeaways
Every Summary Refers to One Collection
Amina can now explain what one staffing-summary row represents. She chooses a department or department-and-city group, then calculates the measures that answer the owner's question. Distinguish counting records from counting present values, and preserve missingness when no amounts are known. Check average's return type on the target system. Select values that match the grouping unit, and order the report explicitly. A summary is useful only when its counts, totals, and labels refer to the same collection.
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 Grouping Rows and Calculating Summaries with GROUP BY
What does GROUP BY do in SQL?
What is the difference between COUNT(*) and COUNT(column)?
Why do I get an error that a column must be in GROUP BY or an aggregate function?
Why does SQL Server return an integer for AVG?
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 →