SQL GROUP BY Clause
The GROUP BY clause is used to group rows together by common column values.
The GROUP BY clause is used in conjunction with the SELECT statement.
The GROUP BY clause is often used with aggregate functions (MIN, MAX, COUNT, AVG, SUM).
Syntax
The basic syntax of GROUP BY can be given with:
SELECT column1_name, column2_name, ...columnN_name, aggregate_function (column_name)
FROM table_name
[WHERE condictions]
GROUP BY column1_name, column2_name, ...columnN_name
[ORDER BY column_name];
Parameters:
colunm1_name, column2_name, ... columnN_name: Columns that are not encapsulated within an aggregate function and must be included in theGROUP BYclause.aggregate_function: This is an aggregate function like MIN, MAX, COUNT, AVG, SUM
Note: The
GROUP BYclause must appear before the ORDER BY, and after the FROM and WHERE clauses.
Demo Table
To understand more the GROUP BY clause, let us suppose that we have a table called "Employee" with the following records:
| emp_no | first_name | last_name | birth_date | hire_date | salary | dept_name |
|---|---|---|---|---|---|---|
| 1001 | James | Smith | 1991-10-23 | 2010-05-13 | 6600 | Customer Service |
| 1002 | Maria | Martinez | 1993-06-13 | 2018-10-08 | 9000 | Development |
| 1003 | Andrew | Rodriguez | 1994-10-25 | 2019-01-23 | 9000 | Finance |
| 1004 | Robert | Hernandez | 1995-09-07 | 2019-09-08 | 9600 | Development |
| 1005 | Donna | Williams | 1996-03-15 | 2012-06-06 | 7400 | Finance |
| 1006 | James | Johnson | 2001-04-30 | 2014-02-18 | 8000 | Marketing |
| 1007 | Stephanie | Miller | 1998-01-17 | 2009-12-12 | 8000 | Human Resources |
| 1008 | Nelson | Lopez | 1999-05-26 | 2010-10-06 | 7300 | Marketing |
SQL GROUP BY - Example
The following SQL statement will find the total number of employees in every department.
SELECT dept_name as "Department", COUNT(emp_no) AS "Number of Employees"
FROM employee
GROUP BY detp_name;
After the execution, the result-set will be as follows:
+------------------+---------------------+ | Department | Number of Employees | +------------------+---------------------+ | Customer Service | 1 | | Development | 2 | | Finance | 2 | | Human Resources | 1 | | Marketing | 2 | +------------------+---------------------+
