The GROUP BY clause is used with a SELECT statement in order to get data that is stored in different records and then bring those results together (“group”) by a certain column or columns.
Structure
SELECT EXPRESSION
FROM TABLE
WHERE [CONSTRAINTS]
GROUP BY [EXPRESSION]
Example
Let’s say when we want to group users by their department, we would do that the following way:
SELECT u.first_name, u.last_name, d.name from users u
JOIN department d on d.id = u.dept_id
WHERE u.active = 1
GROUP BY d.name;