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

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago