MySQL HAVING
The HAVING clause is used to filter groups of records created by the GROUP BY clause. It is similar to the WHERE clause, but is used for aggregate functions.
Examples with Tamil Kings
1. Using HAVING with COUNT
SELECT reign_period, COUNT(*) AS king_count FROM tamil_kings_auto_increment
GROUP BY reign_period
HAVING COUNT(*) > 1;
Code Explanation: This query groups records by reign_period and selects only those groups that have more than one king.
2. Using HAVING with SUM
SELECT kingdom, SUM(reign_years) AS total_reign_years FROM tamil_kings_auto_increment
GROUP BY kingdom
HAVING SUM(reign_years) > 50;
Code Explanation: This query groups records by kingdom and selects only those groups where the total reign years exceed 50.
Best Practices
- Use
HAVINGto filter groups of records based on aggregate functions. - Combine
WHEREandHAVINGfor more precise filtering, usingWHEREto filter rows before grouping andHAVINGto filter groups.
Key Takeaways
- The
HAVINGclause filters groups created byGROUP BY. - It is often used with aggregate functions like
COUNT,SUM, andAVG.