SQL Group By Clause

The Group by clause in SQL has been used in grouping the results of a SELECT query based on one or more columns. It can also be used with the SQL functions to group the result from one or more tables.

Below is the syntax for using Group by in a statement.

SELECT column_name, function(column_name) FROM table_name WHERE condition GROUP BY column_name

 

Example of Group by in a Statement

Let'sLet's consider the Emp table below:

eidnameagesalary
1Mike229000
2John268000
3Rerki216000
4Willi2210000
5Tailor258000

 

In this case, if you want to find the name and age of employees grouped by their salaries, you will be grouping employees based on their salaries, therefore. you will get a data set with unique salary lists, alongside the first employee's name and age that has that salary.

More so, group by is typically used to group different rows of data together based on any one column.

The SQL query for the requirement above will be;

SELECT name, age 
FROM Emp GROUP BY salary

Below is the result;

nameage
Mike22
John26
Rerki21
Willi22

 

Example of Group by in a Statement with WHERE clause

Let’s consider the Emp table

eidnameagesalary
1Mike229000
2John268000
3Rerki216000
4Willi2210000
5Tailor258000

 

SQL query will be,

SELECT name, salary 
FROM Emp 
WHERE age > 25
GROUP BY salary

Below is the result;

eidnameagesalary
2John268000

Never forget, that Group By clause must always come at the end of the SQL query, just like the Order by clause.