MySQL GROUP BY
The GROUP BY
clause is used to group rows that have the same values in specified columns. It is often used with aggregate functions such as COUNT
, SUM
, AVG
, etc., to perform calculations on each group.
Examples with Tamil Kings
1. Grouping by Reign Period
SELECT reign_period, COUNT(*) AS king_count FROM tamil_kings_auto_increment
GROUP BY reign_period;
Code Explanation: This query groups records by reign_period
and counts the number of kings in each group.
2. Using GROUP BY with Multiple Columns
SELECT reign_period, kingdom, COUNT(*) AS king_count FROM tamil_kings_auto_increment
GROUP BY reign_period, kingdom;
Code Explanation: This query groups records by both reign_period
and kingdom
, counting the number of kings in each combination of groups.
Best Practices
- Use
GROUP BY
to aggregate data and derive meaningful insights from groups of records. - Ensure that all columns in the
SELECT
statement that are not aggregated are included in theGROUP BY
clause.
Key Takeaways
- The
GROUP BY
clause groups rows with the same values into summary rows. - It is often used with aggregate functions to summarize data.