GROUP BY combines rows with the same values in one or more columns into groups, allowing aggregate functions to calculate results for each group.
Most business reports require summaries by category, department, region, product, or customer rather than one total for the entire dataset.
Calculate total salary for each department.
SELECT
Department,
SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department;
GROUP BY is fundamental to sales analysis, departmental reporting, regional analysis, customer segmentation, and dashboard preparation.
- GROUP BY creates groups of similar values.
- It is commonly used with aggregate functions.
- Each group produces a summary row.
- Multiple columns can be grouped.
- Non-aggregated selected columns generally need to be included in GROUP BY.
What is GROUP BY used for?
GROUP BY groups rows with the same values so aggregate calculations can be performed for each group.
Can GROUP BY use multiple columns?
Yes. Multiple columns can be used to create groups based on combinations of values.