UPI Study › Courses › Database Programming › Free lessons › Lesson 5.10 Free with a free account
Filtering Grouped Results and Advanced Aggregation with HAVING
Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.10 · lesson 35 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: Data Manipulation Language (DML): Commands at a Glance →← Grouping Rows and Calculating Summaries with GROUP BYNext lesson: Data Manipulation Language (DML): Commands at a Glance →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Filtering groups with HAVING and measuring slices with conditional aggregation.
- Distinguish row filters in WHERE from group filters in HAVING
- Combine several aggregate conditions in a HAVING clause
- Write conditional aggregates with SUM and COUNT over CASE expressions
- Explain how ELSE 0, NULL, and empty input change conditional totals
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,042 words). Read along, or search it.
Opening Question
Departments With Enough Pune Staff
Maya Rao wants a Lantern Books report for departments with enough staff in Pune. Leo filters department totals, but those totals still include people in other cities. Which condition should choose the contributors, and which should choose the completed summaries? Putting both tests in the same place asks the wrong question. Where filters individual records before grouping. Having filters groups after they are formed, and case inside an aggregate can measure selected contributors without removing everyone else.
Clause Order
Row Conditions Versus Aggregate Conditions
Use the same eight illustrative staff records. We can compare whole-department summaries with city-restricted summaries without changing the starting data. Logical order is from, where, group by, having, select, then order by. Physical execution can differ. An aggregate condition tests a count, total, average, minimum, or maximum for a group. Those measures are not available as ordinary row conditions in where. A condition on a grouped key can be legal in having, but a row condition normally belongs in where. Moving other columns there may be invalid or change meaning.
HAVING Basics
Keeping Departments Above a Salary Total
Having tests the completed department total. A department either stays with its summary values, or disappears from the result when its condition fails. Use the aggregate directly in the condition. The threshold applies to the whole group's salary total, rather than to each employee's salary. Run the query. Group by creates the candidate departments, and having keeps those whose sum is greater than ten thousand. IT and Sales remain, while HR is removed. A total exactly equal to the threshold would fail this strict greater-than condition.
Combined Conditions
Testing Maximum Salary and Headcount Together
A having condition can use measures that are not displayed. This report selects only the department label, while testing its largest salary and headcount. Combine group conditions with and or or, just as you combine row predicates. Here both requirements must hold for a group to remain. Run both tests. A single measure would miss part of the requirement. Only IT remains. Sales meets the count requirement but misses the maximum-salary requirement, showing why both aggregate conditions matter.
WHERE and HAVING
Pune Staff First, Then Group Size
Now answer Maya's actual question. Where first keeps Pune employees; group by then builds department groups from that restricted input. Having keeps groups with at least two contributing records. The salary sum therefore describes Pune staff in each retained department, rather than the whole department. Run the staged query. Eight input records become five Pune records, which form three candidate department groups. IT and Sales remain with two Pune staff each. Their totals are twelve thousand five hundred and nine thousand eight hundred; HR has only one Pune employee.
Portability
Aliases in HAVING Differ by Engine
MySQL permits a selected alias in having, and SQLite does too. SQL Server does not permit that same alias reference, so repeat the aggregate for portability. A city test cannot simply move after grouping by department, because a department may contain several cities. A selected city may not describe one group value. An optimizer can move safe predicates. Prefer clear, correct meaning over absolute performance promises.
Conditional Aggregation
SUM of CASE Flags Counts Matches
Conditional aggregation keeps the full group, but lets individual records contribute differently to each measure. Case turns a matching condition into a numeric flag. For the Pune count, a matching record contributes one and another record contributes zero. Sum adds those flags, producing a count of matches. Different expressions measure different slices of the same records. One query can report them together. Run the flags. Every department remains available, even if one conditional count is zero. IT has two Pune staff, one Leeds staff member, and three salaries meeting the threshold. These are overlapping measures, so their counts need not add to headcount.
COUNT Idiom
ELSE Zero Changes What COUNT Counts
Count offers another conditional idiom. Without else, a nonmatching case returns null, which count ignores; matching records return one and are counted. Adding else zero changes that count. Zero is a present value, so count includes the nonmatching records too. Run the two forms together. Their similar spelling hides a different definition of what is being counted. The second measure counts every employee, while the first counts Pune employees. Sum of zero-one flags and count of one-null flags express the intended conditional count.
Zero, Missing, and Empty
Conditional Sums With No Matches
A conditional sum can total matching salaries instead of flags. Without else, a nonmatch contributes null; if no record matches, the sum has no known amounts. An explicit else zero supplies zeros for nonmatching input records. That gives a zero result for this nonempty staff collection with no Oslo matches. There is a separate empty-input case. If where removes every record, even that else expression has no records to evaluate, so ordinary sum still returns null. Run the comparison. Coalesce around the final sum can supply zero for empty input, if policy requires it. The first pair distinguishes missing from zero, and the empty-input summary is null. A default inside case and a default around an aggregate solve different problems.
Conditional HAVING
Filtering Groups on a Conditional Count
A conditional aggregate can also be a having condition. Here each group needs enough salaries meeting the stated individual threshold. The case selects contributions inside each department, then the outer comparison tests their total. The individual threshold and group threshold have different jobs. Run this condition. We do not have to display the conditional count in order to filter on it. IT remains. This pattern combines row-level decisions inside the aggregate with a group-level decision outside, while keeping their roles explicit.
Quick Check
Open Tickets per Team
A new ticket report keeps open tickets, groups by team, then keeps groups with at least two contributing records. Closed tickets are also present in the input. Which team survives both filters? Pause, and decide.
Answer
Only Team A Survives Both Filters
The answer is Team A only. After the open-ticket filter, that team contributes two records, while the other team contributes one. Counting closed tickets would incorrectly let both teams pass. Choosing only Team B reverses which group meets the threshold after the input filter. The real result follows the two stages separately. Where determines the contributors; having decides whether the completed group is large enough.
Key Takeaways
Clear Units and Clear Stages
Maya's department report now counts the intended people before deciding which departments qualify. Its salary totals and headcounts refer to the same restricted input. Use where for contributing records and having for completed group conditions. Repeat aggregate expressions where a selected alias would not be portable. Use case inside aggregates for conditional measures, and distinguish zero, missing, and empty input. Clear units and clear stages make a summary trustworthy.
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 Filtering Grouped Results and Advanced Aggregation with HAVING
What is the difference between WHERE and HAVING in SQL?
Can you use a column alias in a HAVING clause?
What is conditional aggregation in SQL?
Why does COUNT with CASE and ELSE 0 count every row?
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 →