×

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

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 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 SET Operator

In this tutorial, we will understand the operator who falls under the SET operator in SQL with the help of different examples. The SQL SET Operator is used to merge the...

5 minutes read.

SQL INTERSECT

SQL intersect operator is used to combine two or more SELECT statements, but it only displays the data similar to the SELECT statement. The syntax for the INTERSECT operation: SELECT COLUMN_NAME1, COLUMN_NAME2,...

3 minutes read.

SQL LOGICAL Operator

In this tutorial, we will understand the operator who falls under the logical operator in SQL with the help of examples. The SQL Logical Operator displays the query result in one...

5 minutes read.

How to delete a row in SQL

Introduction To delete or remove the unused/unwanted rows from a table, DELETE command is used in SQL.DELETE command removes the entire record from a table.The DELETE statement can delete one or...

6 minutes read.

SQL FOREIGN KEY

In this article, we will learn about the FOREIGN KEY constraints and how to define a FOREIGN KEY constraint to build the relationship between two tables. In a Relational Databases Management...

4 minutes read.

SQL UPDATE

SQL UPDATE The SQL UPDATE statement is utilized to update and modify the records present into a database. It is used to change the already existing records stored in the tables...

3 minutes read.

SQL TABLE

SQL TABLE Structured Query Language (SQL) is a relational database (RDBMS) where data is stored in the form of tables, that is, in rows and columns. These tables are known as...

3 minutes read.

SQL WHERE Multiple Conditions

In this topic, we will learn how to add multiple conditions using the WHERE clause. First, let's understand the concept of WHERE clause. WHERE clause is used to specify a condition while...

5 minutes read.

SQL Commands

SQL commands are classified into four groups on the basis of their nature. DDL (Data Definition Language) DML (Data Manipulation Language) DCL (Data Control Language) DQL (Data Query Language) NOTE: This...

1 minute read.

SQL INSERT Statement

In this tutorial, we will help you to understand and learn how to insert records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

How to compare date in SQL

In this section, we will learn about how dates can be compared in SQL. We can compare any random date with another date stored in a column of a table.This comparison...

4 minutes read.

DDL Commands in SQL

DDL stands for Data Definition Language. Data Definition Language is a bunch of SQL commands used to create, modify and delete Database schema but not the records or data. Data Definition...

5 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

How to use the BETWEEN operator in SQL

In this entire SQL article, we will understand and learn about the BETWEEN operator concept and how to use it in SQL. What is the BETWEEN operator in SQL? The Between operator...

4 minutes read.

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 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.

Commit and Rollback in SQL

In Structured Query Language, we have Data Definition Language (DDL) and Data Manipulation Language (DML) commands the same way we have Transaction Control Language (TCL) commands in the Structured Query...

4 minutes read.

Update Query in SQL

Update is an SQL command that is used to modify the data that in already present in database. Update is a command of DML. DML means Data Manipulation Language. Basically,...

3 minutes read.