Grouping Rows and Calculating Summaries with GROUP BY

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

← 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 →

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

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.

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 Grouping Rows and Calculating Summaries with GROUP BY

What does GROUP BY do in SQL?
GROUP BY collects rows that share the same values in the listed columns into groups, and aggregate functions then return one summary row per group. SELECT department, COUNT(*), SUM(salary) FROM staff GROUP BY department gives each department's headcount and payroll. Grouping by two columns produces one row for each combination that actually occurs. GROUP BY does not guarantee sorted output, so add ORDER BY when order matters.
What is the difference between COUNT(*) and COUNT(column)?
COUNT(*) counts rows, while COUNT(column) counts only rows where that column is not NULL. If two students have scores of 0 and NULL, COUNT(*) returns 2 and COUNT(score) returns 1, because 0 is a recorded value. COUNT(DISTINCT city) counts different non-null cities. For a group whose values are all NULL, COUNT(column) returns 0, while SUM and AVG return NULL.
Why do I get an error that a column must be in GROUP BY or an aggregate function?
The error appears because a grouped query returns one row per group, so every selected column must define the group or be summarized. SQL Server rejects ungrouped columns, and MySQL's default ONLY_FULL_GROUP_BY mode rejects them unless they depend on the grouping key, while SQLite allows them and returns a value from some row in the group. Fix it by adding the column to GROUP BY, which changes the groups, or wrapping it in an aggregate such as MIN(name).
Why does SQL Server return an integer for AVG?
In SQL Server, AVG returns the same type family as its input, so the average of an INT column is truncated to an integer. Cast the input before averaging, as in AVG(CAST(salary AS DECIMAL(10,2))), to keep the fractional part. Casting after AVG cannot recover digits that were already dropped. MySQL returns a DECIMAL average for integer input, and SQLite returns a floating-point value.

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 →