GROUP BY clause is used in a SELECT statement to group “like” records. You can specify one or more columns in the GROUP BY clause. It is used with aggregate functions – to obtain 1 value for a group of rows.
Syntax:
SELECT column1, agg_func(column2) FROM table_name GROUP BY column1;
Consider the employee table as shown below:
id | first_name | last_name | department | salary |
101 | bryan | walker | sales | 50,000 |
102 | alex | carpenter | accounts | 55,000 |
103 | sam | white | sales | 60,000 |
104 | john | barry | sales | 54,000 |
105 | bill | wood | accounts | 65,000 |
106 | robert | hopkins | support | 70,000 |
107 | david | lee | support | 72,000 |
108 | jack | sears | support | 65,000 |
109 | tom | young | sales | 55,000 |
You can use GROUP BY clause to obtain maximum salary in each department as shown below:
SELECT department, max(salary) FROM employee GROUP BY department; department max ---------- ------ sales 60000 accounts 65000 support 72000
Get count of employees in each department as below:
SELECT department, count(id) FROM employee GROUP BY department; department count ---------- ------ sales 4 accounts 2 support 3