WHERE VS HAVING in SQL

Because you need to filter records of a grouped result.

Yes

A WHERE clause is used is filter records from a result. The filter occurs before any groupings are made. A HAVING clause is used to filter values from a group.

You can have situations where you want to filter the selection before the groups are created. For example, if I wanted to list all the exercises where the total calories burned is more than 150 but did not want to include ‘dancing’ as a type, then I would write.

SELECT type, SUM(calories) as total_calories FROM exercise_logs
WHERE type <> 'dancing'
GROUP BY type
HAVING total_calories > 150; 

You will notice the WHERE clause comes before the GROUP BY.

The above would produce;

type total_calories
biking 160
1 Like