MySQL Group By

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.

MySQL Group By Syntax

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.

MySQL Group By Example

Take our "employees" table as an example:

id first_name last_name
1 Paul Pitterson
2 Francine Beecham
3 Raul DiNozzo
4 Anthony DiNozzo

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:

Select last names and count the number of first names in the "employees" table, but group by last name to return only unique last names.

This gives us the desired effect and the result is:

last_name COUNT(first_name)
Beecham 1
DiNozzo 2
Pitterson 1

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.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...