The basic syntax of the GROUP BY
clause is:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
column1
: The column by which to group the results.aggregate_function(column2)
: The aggregate function applied to other columns, like COUNT()
, SUM()
, or AVG()
.Let’s say we have a table employees
with department
and salary
columns, and we want to calculate the total salary for each department:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
In this example:
department
column.SUM()
function to calculate the total salary for each department.You can also use other aggregate functions with GROUP BY
:
Example of counting the number of employees in each department:
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
The GROUP BY
clause is an essential tool for summarizing and aggregating data in MySQL. By grouping rows based on common column values and applying aggregate functions, you can easily analyze data in a structured and meaningful way. Mastering GROUP BY
is key for effective data analysis and reporting in SQL.