In MySQL, the GROUP BY statement is used with aggregate functions to group the resulting data.
Grouping the resulting data is similar to SELECT DISTINCT as it returns only unique values in the column or columns which are being grouped.
The MySQL group by tutorial below will show you how the GROUP BY statement is used.
The syntax for using GROUP BY is given below:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE condition GROUP BY column_name
Remember that the column which you specify to group by will contain only unique values.
Take our "employees" table as an example:
If we wanted to get the amount of persons which have a particular last name we can use the following SQL:
SELECT last_name, COUNT(first_name) FROM employees GROUP BY last_name
Our SQL says:
This gives us the desired effect and the result is:
How it works, is that once we group a column (in this case last_name), we are then able to perform an aggregate function (in this case COUNT) on the group before returning the output to the user.