The having clause in MySQL filters out conditions from a select statement for a group of rows or aggregates.
Having clause is coupled up with the group by clause, and if it is not used in that manner, it would be deemed to be as exact as to where clause.
Syntax
SELECT column_name
FROM table_name
WHERE condition
GROUP BY column_name
HAVING condition;
- The having clause evaluates each group from the group by clause, and when it comes to knowing that the result is true, the row is included in the result set.
- Mysql evaluated the having clause from select, where, group by, and from.
Having Example
SELECT name, city, COUNT(category_id) AS category_count
FROM category
INNER JOIN film_category
USING (category_id)
INNER JOIN inventory
USING(film_id)
INNER JOIN store
USING (store_id)
INNER JOIN address
USING (address_id)
INNER JOIN city
USING (city_id)
GROUP BY name, city
having city = 'Woodridge';
- This is a simple query on the sakila database.
- We are using some inner joins to get the category count of all the films by their category and from which city they belong.
- So here we are going to want a specific city called Woodridge.
- So based on the inner joins, we performed on various tables inside sakila DB to get the category count of the film category.
- We grouped it by city and name.
- And using the having clause, we are thus asking it to filter out from the city called Woodridge.
We can see that it has returned categories from the city Woodridge with its count.
- Log in to post comments