Categories: DBMS

SQL: Group By Clause

The SQL Group By statement is used to organize similar data into groups. The data is further organized using an equivalent function. It means that if multiple rows in a specific column have the same values, they will be grouped.

The SELECT statement is combined with the GROUP BY clause in a SQL query:

  • The WHERE clause comes before the GROUP BY clause in SQL.
  • The ORDER BY clause comes after the GROUP BY clause in SQL.

Syntax:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;

Note: GROUP BY clause is typically used with aggregate functions like SUM, COUNT, AVG, MIN, or MAX to compute summary information for each group.

Example:

Consider an Employee table:

EmpIdFirstNameLastNameSalaryDeptId
1JohnKing330001
2JamesBond330001
3NeenaPatel170002
4LexDe Haan150001
5AmitPatel150001
6AbdulKalam250002
  • Query to count the number of employees in each department:
SELECT DeptId, COUNT(EmpId) as 'Number of Employees' 
FROM Employee
GROUP BY DeptId;

The ‘No of Employees’ column is an abbreviation for the COUNT(EmpId) column. The query returns the following result.

Output:

DeptIdNo of Employees
14
22
  • GROUP BY with WHERE clause:
SELECT EmpId, Salary 
FROM Employee 
WHERE LastName = "Patel"
GROUP BY Salary

The above query is used to select EmpId and Salary with WHERE clause and Group BY clause being on the SALARY column.

Output:

EmpIdSalary
317000
515000

Note: also read about SQL: ORDER BY Clause

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 days ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago