SQL GROUP BY clause
The GROUP BY clause in SQL is used in cooperation with the SELECT statement to sort similar data into groups. This GROUP BY clause follows the WHERE clause in the SELECT statement and precedes the ORDER BY clause.
Syntax
The basic syntax of the GROUP BY clause is shown in the following code block. The SQL GROUP BY clause must comply with the conditions in the WHERE clause and must precede the ORDER BY clause if it is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Example
Suppose the CUSTOMERS table has the following records:
Output:
+----+----------+-----+----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+----------+----------+
| 1 | Ha Anh | 32 | Da Nang | 2000.00 |
| 2 | Van Ha | 25 | Hanoi | 1500.00 |
| 3 | Vu Bang | 23 | Vinh | 2000.00 |
| 4 | Thu Minh | 25 | Hanoi | 6500.00 |
| 5 | Hai An | 27 | Hanoi | 8500.00 |
| 6 | Hoang | 22 | Hanoi | 4500.00 |
| 7 | Binh | 24 | Hanoi | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to know each customer's total salary, the GROUP BY query would look like this.
SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This will produce the following result:
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Binh | 10000.00 |
| Ha Anh | 2000.00 |
| Hai An | 8500.00 |
| Hoang | 4500.00 |
| Thu Minh | 6500.00 |
| Van Ha | 1500.00 |
| Vu Bang | 2000.00 |
+----------+-------------+
Now, let's look at a table where the CUSTOMERS table has the following records with duplicate names:
+----+----------+-----+----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+----------+----------+
| 1 | Ha Anh | 32 | Hanoi | 2000.00 |
| 2 | Ha Anh | 25 | Hanoi | 1500.00 |
| 3 | Vu Bang | 23 | Vinh | 2000.00 |
| 4 | Thu Minh | 25 | Hanoi | 6500.00 |
| 5 | Hai An | 27 | Hanoi | 8500.00 |
| 6 | Hai An | 22 | Hanoi | 4500.00 |
| 7 | Hai An | 24 | Hanoi | 10000.00 |
+----+----------+-----+----------+----------+
Now again, if you want to know the total salary per customer, then the GROUP BY query would be as follows:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
This will produce the following result:
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Ha Anh | 3500.00 |
| Hai An | 23000.00 |
| Thu Minh | 4500.00 |
| Vu Bang | 2000.00 |
+----------+-------------+
Did you find this article helpful?
Support the author so they can write more quality articles!