Use GROUP BY when you need one row per group, such as totals per department
or average salary per role. Any column that is not part of an aggregate function must appear
in the GROUP BY clause.
GROUP BY Syntax and Example
Aggregating data correctly
SELECT group_column, AGGREGATE_FUNCTION(column) AS alias
FROM table_name
GROUP BY group_column;
SELECT Department,
COUNT(*) AS EmployeeCount,
SUM(Salary) AS TotalSalary,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department;
This query returns one row per department with aggregated metrics such as
total employees and average salary.
Filtering GROUP BY Results with HAVING
Post-aggregation filtering
Use HAVING to filter aggregated results. Unlike WHERE,
HAVING works after grouping is complete.
SELECT Department,
COUNT(*) AS EmployeeCount,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000;
The key difference between GROUP BY and ORDER BY in SQL is that
GROUP BY aggregates rows into summary results, while ORDER BY only sorts rows without aggregation.
GROUP BY vs ORDER BY — Quick Comparison
Understand when to use each clause
| Feature |
GROUP BY |
ORDER BY |
| Purpose |
Groups rows into summaries |
Sorts rows for display |
| Common Use |
With aggregate functions |
Sorting query results |
| Result Rows |
One row per group |
All rows reordered |
| Filtering Clause |
HAVING |
WHERE |
| Can Be Used Together? |
Yes — GROUP BY runs first, then ORDER BY sorts the grouped result.
|
Next Step
Learn how to combine GROUP BY and ORDER BY with ASC and DESC.
Continue →
Keywords: group by in SQL, SQL group by example, SQL having clause,
difference between group by and order by in SQL