CodeBlanks Logo Icon CodeBlanks

HAVING vs WHERE

Learn the difference between HAVING and WHERE.

HAVING and WHERE

WHERE filters rows, HAVING filters groups. Both can appear in the same query.

SELECT category, SUM(price)
FROM products
WHERE price > 10
GROUP BY category
HAVING SUM(price) > 100;

This query returns categories whose sum of products over 10 exceeds 100.

category, SUM(price) is selected from products. WHERE keeps only the rows where price > 10 holds. Rows are grouped by category; aggregate functions are computed per group. HAVING SUM(price) > 100 runs after grouping and drops groups that fail the condition.

HAVING and WHERE — details

WHERE narrows rows before GROUP BY; HAVING filters groups after they are formed.

For example, WHERE price > 10 ignores cheap products, then HAVING SUM(price) > 100 picks categories with a high total.

Practice HAVING and WHERE

Use WHERE to pick products over 10, then HAVING to keep category totals over 100.

Starter code

query.sql
-- row and group filter
SELECT category, SUM(price)
FROM products

Sample solution

query.sql
SELECT category, SUM(price)
FROM products
WHERE price > 10
GROUP BY category
HAVING SUM(price) > 100;

Expected output

category  sum
Elektronik 250

Questions and answers

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

1 Add WHERE

Question
SELECT category, SUM(price)
FROM products
____ price > 10
GROUP BY category
HAVING SUM(price) > 100;
Answer
SELECT category, SUM(price)
FROM products
WHERE price > 10
GROUP BY category
HAVING SUM(price) > 100;

Explanation: WHERE filters rows before grouping; HAVING runs after the groups are formed.

2 When does WHERE run?

  • After GROUP BY
  • Before GROUP BY Correct answer
  • After HAVING
  • Last

Explanation: WHERE runs before GROUP BY.

3 HAVING vs WHERE: match the terms

Term Meaning
WHERE row
HAVING group
GROUP BY group by
SUM sum

All lessons in Intermediate