strawquery PT
All lessons

Lesson 25 of 30

WHERE or HAVING?

Today at the studio

The week before the big board meeting, the questions get long, with a filter on the rows and another on the groups. Kou's last note appears under the keyboard: "order matters. FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY, then LIMIT."

The idea

SQL reads the query in a different order than you write it: first FROM and JOIN, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY and finally LIMIT.

That is why WHERE cannot see an alias made in SELECT, and why a row filter belongs in WHERE while a filter on a total belongs in HAVING. When a query looks tricky, read it in this order.

Example

SELECT species, COUNT(*)
FROM characters
WHERE voice_actor = 'Maya Lin'
GROUP BY species
HAVING COUNT(*) > 1

Your turn

0 of 4 questions

Question 1 of 4

Looking only at finished shows, which genres have more than one show? Show genre and the count.

Unofficial fan project. Titles belong to their creators and rights holders.