HAVING Clause in SQL

Level 387 keystrokes

HAVING filters groups after GROUP BY, unlike WHERE which filters rows.

SQL code

-- Return each category and its number of products
1SELECT
2 category,
-- COUNT(*) counts the rows in each group
3 COUNT(*) AS total
4FROM
5 products
-- Make one group per category
6GROUP BY
7 category
-- HAVING runs after grouping: keep only categories with more than 5 products
-- WHERE could not do this, because it filters rows before COUNT is known
8HAVING
9 COUNT(*) > 5;

Output

+-------------+-------+
| category    | total |
+-------------+-------+
| Electronics |    12 |
| Clothing    |     8 |
+-------------+-------+
2 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • (× 2
  • )× 2
  • *× 2
  • ,× 1
  • ;× 1
  • >× 1

More SQL examples at level 3

← SQL typing practice