sajad torkamani

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):

  1. Read through every record in the employees table (evaluate FROM clause).
  2. 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 (evaluate GROUP BY clause).
  3. 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