DELAPARRA
Index
Color
NL
Category: SQL

HAVING

Explained by Updated

What is HAVING?

HAVING: Filters AFTER grouping, on aggregate results. WHERE filters rows before grouping; HAVING filters groups. HAVING filters groups after GROUP BY has done its work. WHERE filters individual rows before grouping; HAVING filters on the results of aggregates. SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) > 5 finds customers with more than five orders. You cannot write that condition in WHERE, because the count does not exist yet at that point.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about HAVING

What should you keep in mind with HAVING?

Use both together when you can. Filter as many rows as possible with WHERE first, such as orders from this year, then filter groups with HAVING. That way the database groups fewer rows and the query runs faster. A condition on a plain column belongs in WHERE, even though HAVING would technically accept it in some databases.

What does an example of HAVING look like?

SELECT user_id, COUNT(*) AS n FROM orders GROUP BY user_id HAVING COUNT(*) > 5;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with H

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.