GROUP BY makes one group per value, and COUNT(*) counts the rows in each group. Often you want only some of the groups: the categories with many products, or the cities with many customers. That needs a filter on the groups.
WHERE can't do it. It checks single rows, before any group is made, so there is no count to test yet: COUNT(*) inside WHERE is an error. HAVING is the filter for groups. It comes after GROUP BY and can test each group's count. For example, the cities with at least two customers:
SELECT city, COUNT(*)
FROM customers
GROUP BY city
HAVING COUNT(*) >= 2
A short rule: WHERE filters rows, HAVING filters groups. One query can use both, with WHERE before GROUP BY and HAVING after it.
Your query must print the categories that have more than two products, with their count:
category | COUNT(*) office | 3 (1 row)
Your task: the starting code already connects db to shop.db and opens query = ( … ). Inside it, write one string piece per clause: select category and COUNT(*) from products, group by category, and keep only the groups whose count is more than 2.
Assignment
Follow the Coding Tutorial to write the query one clause at a time, from SELECT to HAVING.
Hint
End every string piece with a space, so the pieces join into one query. HAVING goes after GROUP BY. home and kitchen have exactly 2 products each, so use >, not >=.
Free plan: 30 tutor messages. PRO is unlimited.
