SQL: Group By Clause

  • March 28, 2023
  • DBMS
SQL Views

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

Leave a Reply

Your email address will not be published. Required fields are marked *