×

How to use GROUP BY clause in SQL

In this SQL article, we will learn about the GROUP BY clause and how to use it in SQL. We will also discuss using the GROUP BY clause with the WHERE clause.

What is the GROUP BY clause?

The GROUP BY clause is an SQL clause used in the SELECT statement to manage the same records of a column in the group using SQL functions.

Syntax of GROUP BY clause:

SELECT columnname1, columnname2, columnname3 FROM tablename GROUP BY columnname;

We can use multiple columns from the table in the GROUP BY clause.

There are some steps, we have to learn for how to use the GROUP BY clause in the SQL query:

1. Create a new database or use an existing database by selecting the database using the USE keyword followed by the database name.

2. Create a new table inside the selected database, or you can use an already created table.

3. If the table is newly created, insert the records in the newly created database using the INSERT query and view the inserted data using the SELECT query without the GROUP BY clause.

4. Now, we are ready to use the GROUP BY clause in the SQL queries.

Step 1: Create a new database or use an already created database.

I have already created a database. I will use my existing created database name, Company.

USE Company;

Company is the database name.

Those who didn’t have created a database follow the below query to create the database:

CREATE DATABASE database_name;

After creating the database, select the database using the USE keyword followed by the database name.

Step 2: Create a new table or use already existing table:

I have already created a table. I will use the existing table named Employees.

To create the new tables, follow the below CREATE TABLE syntax:

CREATE TABLE table_name(

columnname1 datatype(column size),

columnname2 datatype(column size),

columnname3 datatype(column size)

);

Step 3: Insert the records in the newly created table using the INSERT query and view the records using the SELECT query.

Use the following syntax to insert new records in the table:

INSERT INTO table_name VALUES(value1, value2, value3);

Use the following syntax to view the records from the table:

SELECT * FROM table_name;

The following query will display the records of Employees:

SELECT * FROM Employees;

The output of the above SELECT query is:

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
1001VAIBHAVIMISHRA65500PUNEORACLE1
1002VAIBHAVSHARMA60000NOIDAC#5
1003NIKHILVANI50500JAIPURFMW2
2001PRACHISHARMA55500CHANDIGARHORACLE1
2002BHAVESHJAIN65500PUNEFMW2
2003RUCHIKAJAIN50000MUMBAIC#5
3001PRANOTISHENDE55500PUNEJAVA3
3002ANUJAWANRE50500JAIPURFMW2
3003DEEPAMJAUHARI58500MUMBAIJAVA3
4001RAJESHGOUD60500MUMBAITESTING4
4002ASHWINIBAGHAT54500NOIDAJAVA3
4003RUCHIKAAGARWAL60000DELHIORACLE1
5001ARCHITSHARMA55500DELHITESTING4
5002SANKETCHAUHAN70000HYDERABADJAVA3
5003ROSHANNEHTE48500CHANDIGARHC#5
6001RAHULNIKAM54500BANGALORETESTING4
6002ATISHJADHAV60500BANGALOREC#5
6003NIKITAINGALE65000HYDERABADORACLE1

Step 4: We are ready to use the GROUP BY clause in the queries

We will now take deep dive into the GROUP BY clause with the help of examples

Example 1: Write a query to display the employee records group by city.

SELECT * FROM EMPLOYEES GROUP BY CITY;

The above query displays the employees' records where an employee from the same city will be considered one group. For example, if there are 10 employees records in table where 3 are from Pune city, 3 are from Mumbai city, 2 are from Hyderabad and Bangalore, then the above query will group Pune city employee Mumbai city employee as one record, and so on.

The output of the above query:

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
6001RAHULNIKAM54500BANGALORETESTING4
2001PRACHISHARMA55500CHANDIGARHORACLE1
4003RUCHIKAAGARWAL60000DELHIORACLE1
5002SANKETCHAUHAN70000HYDERABADJAVA3
1003NIKHILVANI50500JAIPURFMW2
2003RUCHIKAJAIN50000MUMBAI C# 5
1002VAIBHAVSHARMA60000NOIDAC#5
1001VAIBHAVIMISHRA65500PUNEORACLE1
How To Use GROUP BY Clause In SQL

As we can see that the employees' records are grouped by city, and records are displayed in the ascending order by default.  

Example 2: Write a query to display employees' records group by salary in descending order.

SELECT * FROM EMPLOYEES GROUP BY SALARY DESC; 

The above query displays the employees' records where employees with the same salary will be considered one group, and records will display in descending order.

The output of the above query:

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
5002SANKETCHAUHAN70000HYDERABADJAVA3
1001VAIBHAVIMISHRA65500PUNEORACLE1
6003NIKITAINGALE65000HYDERABADORACLE 1
4001RAJESHGOUD60500MUMBAITESTING 4
1002VAIBHAVSHARMA60000NOIDAC#5
3003DEEPAMJAUHARI58500MUMBAIJAVA 3
2001PRACHISHARMA55500CHANDIGARHORACLE1
4002ASHWINIBAGHAT54500NOIDAJAVA 3
1003NIKHILVANI50500JAIPURFMW2
2003RUCHIKAJAIN50000MUMBAI C# 5
5003ROSHANNEHTE48500CHANDIGARHC# 5
How To Use GROUP BY Clause In SQL

As we can see, the employees' records are grouped by salary, and records are displayed in descending order, as we mention desc at the end.

Example 3: Write a query to display employees’ records group by salary and city.

SELECT * FROM EMPLOYEES GROUP BY SALARY, CITY;

The above query displays the employees' records where employees with the same salary and city will be considered one group.

For example, suppose the table had 10 employee records. From 10 employees 2 employees' salary and city matches with other two employees and rest six employees salary and city is unmatched then the 6 employees will be considered as 6 separate groups, and 2 employees who match with other 2 employees will be considered as one group. In short, 8 groups will be formed.

The output of the above query:

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
5003ROSHANNEHTE48500CHANDIGARHC#5
2003RUCHIKAJAIN50000MUMBAIC#5
1003NIKHILVANI50500JAIPURFMW2
6001RAHULNIKAM54500BANGALORETESTING4
4002ASHWINIBAGHAT54500NOIDAJAVA3
2001PRACHISHARMA55500CHANDIGARHORACLE1
5001ARCHITSHARMA55500DELHITESTING4
3001PRANOTISHENDE55500PUNEJAVA3
3003DEEPAMJAUHARI58500MUMBAIJAVA3
4003RUCHIKAAGARWAL60000DELHIORACLE1
1002VAIBHAVSHARMA60000NOIDAC#5
6002ATISHJADHAV60500BANGALOREC#5
4001RAJESHGOUD60500MUMBAITESTING4
6003NIKITAINGALE65000HYDERABADORACLE1
1001VAIBHAVIMISHRA65500PUNEORACLE1
5002SANKETCHAUHAN70000HYDERABADJAVA3
How To Use GROUP BY Clause In SQL

As we can see, the employees' records are grouped by salary and city, and records are displayed in ascending order by default. 

Example 4: Write a query to display employees' records by city and department.

SELECT * FROM EMPLOYEES GROUP BY CITY, DEPARTMENT;

The above query displays the employees' records where employees are in the same city, and the department will be considered one group.

The output of the above query:

EMPLOYEEIDFIRST_NAMELAST_NAMESALARYCITYDEPARTMENTMANAGERID
6002ATISHJADHAV60500BANGALOREC#5
6001RAHULNIKAM54500BANGALORETESTING4
5003ROSHANNEHTE48500CHANDIGARHC#5
2001PRACHISHARMA55500CHANDIGARHORACLE1
4003RUCHIKAAGARWAL60000DELHIORACLE1
5001ARCHITSHARMA55500DELHITESTING4
5002SANKETCHAUHAN70000HYDERABADJAVA3
6003NIKITAINGALE65000HYDERABADORACLE1
1003NIKHILVANI50500JAIPURFMW2
2003RUCHIKAJAIN50000MUMBAIC#5
3003DEEPAMJAUHARI58500MUMBAIJAVA3
4001RAJESHGOUD60500MUMBAITESTING4
1002VAIBHAVSHARMA60000NOIDAC#5
4002ASHWINIBAGHAT54500NOIDAJAVA3
2002BHAVESHJAIN65500PUNEFMW2
3001PRANOTISHENDE55500PUNEJAVA3
1001VAIBHAVIMISHRA65500PUNEORACLE1
How To Use GROUP BY Clause In SQL

As we can see, the employees' records are grouped by city and department, and records are displayed in ascending order by default. 

Example 5: Write a query to count the list of employees in each department from the employees' table.

SELECT DEPARTMENT, COUNT(DEPARTMENT) FROM EMPLOYEES GROUP BY DEPARTMENT;

The above query displays the count of employees in each department group by the department. Like Six employees work in the HR department, five work in another department.

The output of the above query:

DEPARTMENTCOUNT(DEPARTMENT)
C#4
FMW3
JAVA4
ORACLE4
TESTING3
How To Use GROUP BY Clause In SQL

As we can see, four employees work in C# Department, three work in FMW Department, etc.

Example 6: Write a query to count the list of employees from each city from the employees' table.

SELECT CITY, COUNT(CITY) FROM EMPLOYEES GROUP BY CITY;

The above query displays the count of employees in each city group by city. Like three employees work from Pune city, four work from another city, and so on.

The output of the above query:

CITYCOUNT(CITY)
BANGALORE2
CHANDIGARH2
DELHI2
HYDERABAD2
JAIPUR2
MUMBAI3
NOIDA2
PUNE3
How To Use GROUP BY Clause In SQL

As we can see, two employees work from Bangalore city, three works from Mumbai city, and so on.

Example 7: Write a query to sum the employee salary group by the city.

SELECT CITY, SUM(SALARY) AS SALARY FROM EMPLOYEES GROUP BY CITY;

The above is used to sum the employees' salaries grouped by the city name. For example, for employees from the same city, their salary will be the sum and considered one group. We used the aggregate sum function followed by the salary column for adding salary.

The output of the above query:

CITYSALARY
BANGALORE115000
CHANDIGARH104000
DELHI115500
HYDERABAD135000
JAIPUR101000
MUMBAI169000
NOIDA114500
PUNE186500
How To Use GROUP BY Clause In SQL

As we can see, Bangalore city sum salary is 115000, Chandigarh city sum salary is 104000 which is the addition of different employee salary, but from the city, the same approach is used for each city.

Example 8: Write a query to find the minimum salary from each department.

SELECT DEPARTMENT, MIN(SALARY) FROM EMPLOYEES GROUP BY DEPARTMENT;

The above query is used to find the employee's minimum salary from each department. One of the employees from the Java department's salary is 54500, which is the lowest in over the entire java department. The same 48500 is the lowest salary paid to the employee in the C# department.

The output of the above query:

DEPARTMENTMIN(SALARY)
C#48500
FMW50500
JAVA54500
ORACLE55500
TESTING54500
How To Use GROUP BY Clause In SQL

As we can see, 50500 is the lowest salary paid to one of the employees in the FMW department, 55500 is the lowest salary paid to one of the employees in the ORACLE department.

Example 9: Write a query to find the minimum salary from each city.

SELECT CITY, MAX(SALARY) FROM EMPLOYEES GROUP BY CITY;

The above query is used to find the maximum salary from each city. One of the employees from the Pune city salary is 65500 which is the highest in over the entire Pune city, same 60500 is the highest salary paid to the employee in the Mumbai city.

The output of the above query:

CITYMAX(SALARY)
BANGALORE60500
CHANDIGARH55500
DELHI60000
HYDERABAD70000
JAIPUR50500
MUMBAI60500
NOIDA60000
PUNE65500
How To Use GROUP BY Clause In SQL

As we can see, 50500 is the highest salary paid to one of the employees in Jaipur city, 55500 is the highest salary paid to one of the employees in Chandigarh city.


Related Topics

Difference between SQL and NoSQL

SQL vs. NoSQL | Difference between SQL and NoSQL Choosing a database is the most fundamental decision that needs to be decided before starting a task. Relational and non-relational databases are...

3 minutes read.

SQL Operators

Arithmetic Operators Arithmetic operators are +, -, *, /, % performs addition, subtraction, multiplication, division, modulo respectively. Example:   Select 100+222; Select salary+100 From teacher Where teacher_id=1; Following output screen shows different arithmetic operations. We...

2 minutes read.

Codd’s Rules in SQL

Codd’s Rules Dr. Edgar F. Codd, in 1985, laid down 13 fundamental rules after doing large-scale research on the Relational Model of databases. According to him, every database must follow these...

3 minutes read.

WHERE Clause vs HAVING Clause

The WHERE Clause and HAVING clause filter the records in the Structured Query Language queries. The main difference between the WHERE clause and the HAVING clause is the WHERE clause...

5 minutes read.

SQL Wildcards

SQL WILDCARD CHARACTERS: SQL wild card character is used to substitute zero or more characters of a string. These characters are used with the “LIKE” operator. Wild Card Characters in SQL: %_[]^- “%” : It is...

3 minutes read.

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

TCL Commands in SQL

In Structured Query Language, TCL is an abbreviation for Transaction Control Language. A single unit of work in a database is formed after the consecutive execution of commands is known...

6 minutes read.

How to use INNER JOIN in SQL

In this article, we will learn about the INNER JOIN concept and how to use it in SQL with the WHERE clause. What is INNER JOIN in SQL? Inner Join is a...

6 minutes read.

SQL Create Database

This tutorial will help us understand how to CREATE a Database in SQL with a few examples. The first step for storing structured records in the database is creating the databases. We...

4 minutes read.

SQL Select Distinct

The SQL DISTINCT query is used to fetch unique values from the tables using the SELECT statement in the SQL. There may be a situation that arises when you want to...

4 minutes read.

SQL COPY Table

In this tutorial, we will learn how to copy tables in SQL with the help of examples. Using the SELECT INTO statement in the SQL we can copy one table into...

4 minutes read.

Truncate function in SQL

The TRUNCATE is a numeric function in SQL which truncates the number according to the particular decimal points. Syntax of TRUNCATE Function SELECT TRUNCATE(X, D) AS Alias_Name; In the TRUNCATE syntax, X...

4 minutes read.

SQL Syntax

In this tutorial, we will help you understand about the different SQL Syntax concepts with the help of an example. Every Structured Query Language starts with Keywords like select, insert, update,...

5 minutes read.

SQL Auto Increment

As we all know, In SQL for unique identification, we assign a column with the primary key. But in some tables, we find difficult to differentiate a column as a...

5 minutes read.

SQL Truncate

This command deletes all records from table. Truncate is a DDL command. Syntax: TRUNCATE table table_name; Example: Truncate table teacher; ORDER BY The ORDER BY clause arranges the table or column in ascending...

5 minutes read.

How to use LIKE in SQL

In this SQL article, we will learn and understand how to use LIKE to the columns in the SQL tables. What is Like? Like is an operator in the SQL. It is...

7 minutes read.

SQL SELECT WHERE Clause

In this SQL section, we will help you understand the concept of the SQL SELECT WHERE clause with a few examples. The WHERE clause in SELECT query displays those records as...

5 minutes read.

SQL SELECT MAX

The SQL Max() function is an aggregate function in SQL. This function returns the values which are greater in the condition. The condition may be a number, or it may...

5 minutes read.

SQL Top Clause

Top Clause: It returns the first ‘n’ number of rows as output. This Top clause is used to retrieve the required number of rows when there are thousands of records stored...

3 minutes read.

SQL SubQuery

The Sub-query in the SQL is the inner query placed or positioned inside another query, which is also known is the outer query. The inner query is embedded in the...

6 minutes read.