CodeBlanks Logo Icon CodeBlanks

What is HAVING?

Filter groups with HAVING.

What is HAVING?

HAVING filters groups. WHERE filters rows, HAVING filters groups.

SELECT category, COUNT(*)
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

This query returns categories with more than 5 products.

category, COUNT(*) is selected from products. Rows are grouped by category; aggregate functions are computed per group. HAVING COUNT(*) > 5 runs after grouping and drops groups that fail the condition.

What is HAVING? — details

HAVING runs after aggregation. WHERE is applied before GROUP BY, HAVING after.

For example, HAVING COUNT(*) > 5 keeps only categories with more than 5 products; you can't put this in WHERE because the count hasn't been computed yet.

Practice What is HAVING?

Find categories with more than 5 products using HAVING COUNT(*) > 5.

Starter code

query.sql
-- filter groups
SELECT category, COUNT(*)
FROM products
GROUP BY category

Sample solution

query.sql
SELECT category, COUNT(*)
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

Expected output

category  count
Elektronik 8
Kitap     12

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does HAVING filter?

  • Groups Correct answer
  • Rows
  • Columns
  • Tables

Explanation: HAVING filters groups.

2 Add HAVING

Question
SELECT category, COUNT(*)
FROM products
GROUP BY category
____ COUNT(*) > 5;
Answer
SELECT category, COUNT(*)
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

Explanation: HAVING filters groups; COUNT(*) > 5 keeps only categories with more than 5 products.

3 What is HAVING: match the terms

Term Meaning
HAVING group filter
WHERE row filter
GROUP BY group
COUNT count

All lessons in Intermediate