GROUP BY Clause

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax

The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example

Consider the CUSTOMERS table is having the following records −

IDNAMEAGEADDRESSSALARY
1Ramesh32Ahmedabad2000.00
2Khilan25Delhi1500.00
3kaushik23Kota2000.00
4Chaitali25Mumbai6500.00
5Hardik27Bhopal8500.00
6Komal22MP4500.00
7Muffy24Indore10000.00

If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows.

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

This would produce the following result −

NAMESUM(SALARY)
Chaitali6500.00
Hardik8500.00
kaushik2000.00
Khilan1500.00
Komal4500.00
Muffy10000.00
Ramesh2000.00

Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names −

IDNAMEAGEADDRESSSALARY
1Ramesh32Ahmedabad2000.00
2Ramesh25Delhi1500.00
3kaushik23Kota2000.00
4kaushik25Mumbai6500.00
5Hardik27Bhopal8500.00
6Komal22MP4500.00
7Muffy24Indore10000.00

Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows −

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

This would produce the following result −

NAMESUM(SALARY)
Hardik8500.00
kaushik8500.00
Komal4500.00
Muffy10000.00
Ramesh3500.00
sql rdbms group-by

Subscribe For More Content