SQL Group By
Clause
Group by clause is used to group the results of a SELECT
query based on one or more columns. It is also used with SQL functions to group the result from one or more tables.
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
Consider the following Emp table.
eid | name | age | salary |
401 | Anu | 22 | 9000 |
402 | Shane | 29 | 8000 |
403 | Rohan | 34 | 6000 |
404 | Scott | 44 | 9000 |
405 | Tiger | 35 | 8000 |
Here we want to find name and age of employees grouped by their salaries or in other words, we will be grouping employees based on their salaries, hence, as a result, we will get a data set, with unique salaries listed, along side the first employee's name and age to have that salary. Hope you are getting the point here!
group by
is used to group different row of data together based on any one column.
SQL query for the above requirement will be,
SELECT name, age
FROM Emp GROUP BY salary
Result will be,
name | age |
Rohan | 34 |
Shane | 29 |
Anu | 22 |
Example of Group by
in a Statement with WHERE
clause
Consider the following Emp table
eid | name | age | salary |
401 | Anu | 22 | 9000 |
402 | Shane | 29 | 8000 |
403 | Rohan | 34 | 6000 |
404 | Scott | 44 | 9000 |
405 | Tiger | 35 | 8000 |
SQL query will be,
SELECT name, salary
FROM Emp
WHERE age > 25
GROUP BY salary
Result will be.
name | salary |
Rohan | 6000 |
Shane | 8000 |
Scott | 9000 |
You must remember that Group By
clause will always come at the end of the SQL query, just like the Order by
clause.