GROUP BY
The group by clause is used for grouping the records of the database table according to our need. Which is an optional part of SELECT statement.
SYNTAX
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
The GROUP BY clause must appear after the FROM and WHERE clauses
Example of Group by in a Statement. Consider following Employee table
Employee_id | Employee_name | salary |
---|---|---|
1 | Appu | 9000 |
2 | Ammu | 8000 |
3 | Achu | 6000 |
4 | Arathy | 10000 |
5 | Ashwathi | 8000 |
Name |
---|
Achu |
Ammu |
Appu |
Arathy |
Example of Group by in a Statement with WHERE clause
Employee_id | Employee_name | salary |
---|---|---|
1 | Appu | 9000 |
2 | Ammu | 8000 |
3 | Achu | 6000 |
4 | Arathy | 10000 |
5 | Ashwathi | 8000 |
Employee_name | salary |
---|---|
Ashwathi | 8000 |
NOTE: Group By clause will always come at the end, just like the Order by clause.
HAVING
The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used.
SYNTAX
select column_name, function(column_name)
FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition
Example
Employee_id | Employee_name | salary |
---|---|---|
1 | Appu | 2000 |
2 | Ammu | 1000 |
3 | Achu | 2000 |
4 | Arathy | 1000 |
5 | Appu | 2000 |
Employee_id | Employee_name | salary |
---|---|---|
1 | Appu | 2000 |
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.