GROUP BY Clause

SQL AggregationGroupingFree Lesson

Advertisement

The GROUP BY Clause

The GROUP BY clause groups rows that have the same values so you can calculate aggregate statistics for each group.

💡 GROUP BY is the foundation of data aggregation in SQL.

Basic Syntax

SELECT column1, aggregate_function(column2)
FROM table_name

GROUP BY column1
;

Example

SELECT department, COUNT(*) AS employee_count, ROUND(AVG(salary), 2) AS avg_salary
FROM employees

GROUP BY department

ORDER BY avg_salary DESC;

WHERE vs HAVING

ClauseFiltersWhenCan Use Aggregates
WHEREIndividual rowsBefore GROUP BYNo
HAVINGGroupsAfter GROUP BYYes

✏️ Exercise: Write a query that uses GROUP BY to count employees per department

See Solution


SELECT department, COUNT(*) AS count
FROM employees
GROUP BY department

ORDER BY count DESC;

✅ Key Takeaways

  1. GROUP BY groups rows for aggregate calculations
  2. Use with aggregate functions like COUNT, SUM, AVG, MIN, MAX
  3. WHERE filters individual rows BEFORE grouping
  4. HAVING filters groups AFTER grouping
  5. ORDER BY comes last after GROUP BY and HAVING

Advertisement

Need Expert SQL Help?

Get personalized SQL training or database consulting.

Advertisement