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
Let'sLet's consider the Emp table below:
eid | name | age | salary |
---|---|---|---|
1 | Mike | 22 | 9000 |
2 | John | 26 | 8000 |
3 | Rerki | 21 | 6000 |
4 | Willi | 22 | 10000 |
5 | Tailor | 25 | 8000 |
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;
name | age |
---|---|
Mike | 22 |
John | 26 |
Rerki | 21 |
Willi | 22 |
Let’s consider the Emp table
eid | name | age | salary |
---|---|---|---|
1 | Mike | 22 | 9000 |
2 | John | 26 | 8000 |
3 | Rerki | 21 | 6000 |
4 | Willi | 22 | 10000 |
5 | Tailor | 25 | 8000 |
SQL query will be,
SELECT name, salary
FROM Emp
WHERE age > 25
GROUP BY salary
Below is the result;
eid | name | age | salary |
---|---|---|---|
2 | John | 26 | 8000 |
Never forget, that Group By clause must always come at the end of the SQL query, just like the Order by clause.