HAVING: Using the HAVING Clause in SQL: Filtering Aggregated Data

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


Welcome back to our ongoing series on SQL programming. In this edition, we’re going to cover HAVING, a clause in SQL that allows you to filter aggregated data.
Let’s start by understanding why we need to use HAVING clause in SQL.

Why use HAVING

The WHERE clause in SQL is a powerful tool for filtering rows of data based on condition(s). But when combined with aggregate functions like COUNT(), SUM(), AVG(), it can’t be used for filtering the aggregated data. This is where HAVING comes into play.

When to use HAVING

The general rule of thumb is to use HAVING when you want to filter results after an aggregation has taken place.

Basic Syntax

Examples

Example 1: Using COUNT with HAVING

Imagine you have a table ‘orders’ and you want to find out only those ‘product categories’ from it, which have more than 5 entries.

Example 2: Using SUM with HAVING

Now imagine that you want to filter out only rows with total sale being more than a certain value.

Conclusion

That’s all for the basics of SQL HAVING clause. The HAVING clause is a very powerful SQL operator and can greatly simplify our work when it comes to filtering aggregated data. Just remember that it works hand-in-hand with GROUP BY for filtering groups based on specific conditions.

Leave a Comment