New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› SQL› Aggregates and Grouping

Aggregates and Grouping

💻 SQL

Summarise data with COUNT, SUM, AVG and GROUP BY.

Lesson 3 of 9 Tutorial
0 of 9 completed

Aggregates turn many rows into one number. Grouping lets you produce one number per category.

By the end of this lesson you can:
  • Use COUNT, SUM, AVG, MIN and MAX.
  • Group rows with GROUP BY.
  • Filter groups with HAVING.

Aggregate Functions

An aggregate takes many rows and returns one value.

SELECT COUNT(*) AS total_students,
       AVG(score) AS average_score,
       MAX(score) AS best_score
FROM students;

GROUP BY

Group rows that share a value, then aggregate inside each group. Every column in the SELECT that is not aggregated should appear in GROUP BY.

SELECT level,
       COUNT(*) AS students,
       ROUND(AVG(score), 1) AS average_score
FROM students
GROUP BY level
ORDER BY level;

HAVING

WHERE filters rows before grouping. HAVING filters groups after aggregation.

SELECT level, AVG(score) AS average_score
FROM students
GROUP BY level
HAVING AVG(score) >= 65;
Tip COUNT(*) counts rows. COUNT(column) ignores NULL values in that column. Choose deliberately.

Practice

  1. Count students in each level.
  2. Find the highest score in SS2.
  3. Show levels where the average score is below 50.

Hands-on exercise

Given a sales table with product and amount, write a query that returns each product, the number of sales and the total amount. Include only products with a total above 1000, sorted by total descending.

Recap

Aggregates summarise rows, GROUP BY creates one summary per category, and HAVING filters those summaries.

Example

SELECT COUNT(*) AS total_students,
       AVG(score) AS average_score,
       MAX(score) AS best_score
FROM students;

Exercises

Exercise 1. Sales summary Medium
Given a sales table with product and amount, write a query that returns each product, the number of sales and the total amount. Include only products with a total above 1000, sorted by total descending.
SQL exercise-1.sql
Expected Output
One row per qualifying product with count and total.

Lesson Nav

Lesson sections