SQL: GROUP BY reference
19 March 2023 (Updated 10 March 2024)
On this page
In a nutshell
The GROUP BY
clause groups rows by one or more column values. It is typically used together with an aggregate function like COUNT()
to group rows by one or more columns and perform calculations on them (e.g., find the max employee salary for each department).
Example & execution plan
select gender, count(*)
from employees
group by gender;
SQL will execute the above query in the following steps (keep in mind the logical processing order):
- Read through every record in the
employees
table (evaluateFROM
clause). - For each record, add it to the group where the other records also have the same column value for
gender
. If there are no other records yet for that group, create the group and add the current record to it (evaluateGROUP BY
clause). - After going through all the records, read through each group and return the gender and count of records in that group (evaluate
SELECT
clause).
Sources
Tagged:
MySQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment