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 perform calculations on the groups.

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


Tagged: MySQL