Filtering Grouped Results and Advanced Aggregation with HAVING

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

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

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

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.

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 Filtering Grouped Results and Advanced Aggregation with HAVING

What is the difference between WHERE and HAVING in SQL?
WHERE filters individual rows before grouping, while HAVING filters whole groups after aggregates are calculated. In SELECT department, SUM(salary) FROM staff WHERE city = 'Pune' GROUP BY department HAVING COUNT(*) >= 2, only Pune staff are grouped, and only departments with at least two of them remain. Aggregate functions cannot appear directly in that query's WHERE, because groups do not exist yet at that stage.
Can you use a column alias in a HAVING clause?
It depends on the database: MySQL and SQLite accept a SELECT alias in HAVING, but SQL Server does not, because it evaluates HAVING before the SELECT list. Repeating the aggregate, as in HAVING SUM(salary) > 10000, works in all three. HAVING can also test aggregates that are not displayed, such as MAX(salary) or COUNT(*), and combine several tests with AND or OR.
What is conditional aggregation in SQL?
Conditional aggregation places a CASE expression inside an aggregate so one grouped query can measure several slices at once. SUM(CASE WHEN city = 'Pune' THEN 1 ELSE 0 END) counts Pune staff in each department, and SUM(CASE WHEN salary >= 5000 THEN 1 ELSE 0 END) counts higher earners in the same result row. Because the slices can overlap, their counts need not add up to the headcount.
Why does COUNT with CASE and ELSE 0 count every row?
COUNT counts every non-null value, and 0 is not NULL, so COUNT(CASE WHEN city = 'Pune' THEN 1 ELSE 0 END) counts every row. Drop the ELSE, as in COUNT(CASE WHEN city = 'Pune' THEN 1 END), or switch to SUM with ELSE 0. With SUM, no ELSE and no matching rows give NULL, while ELSE 0 gives 0. Over empty input, SUM returns NULL either way, so wrap it in COALESCE when zero is wanted.

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 →