SQL Tutorial

GROUP BY and Aggregate Functions

Summarize data with COUNT, SUM, AVG, MIN, MAX, GROUP BY and HAVING.

Concept

Aggregate functions collapse many rows into summary values. GROUP BY creates one aggregate result per group, while HAVING filters those groups after aggregation.

Be precise about the level of detail you want. Adding extra grouping columns changes the meaning of the result.

Example

SELECT city, COUNT(*) AS student_count
FROM students
GROUP BY city
HAVING COUNT(*) >= 2
ORDER BY student_count DESC;
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Count students by city.
  2. Find average fee by course category.
  3. Use HAVING to keep only groups above a threshold.

Key Takeaways

  • Aggregates summarize rows.
  • GROUP BY defines the grouping grain.
  • HAVING filters grouped results.