Chapter 10: Aggregate Functions

Up until now, we’ve been looking at individual rows — one book, one author, one order at a time. Now we’re going to summarize huge amounts of data:

  • How many books do we have in total?
  • What’s the average price?
  • Who is the most expensive author?
  • How many books per author?

The magic words here are aggregate functions + GROUP BY + HAVING.

We’ll cover:

  • COUNT, SUM, AVG, MIN, MAX — the main aggregate functions
  • GROUP BY — group rows that have the same values
  • HAVING — filter groups (like WHERE, but for after grouping)

We’ll use our familiar bookshop database with the books and authors tables.

Sample Data Reminder (books table – let’s add a few more rows for better examples)

book_id title author_id price stock category
1 The Room on the Roof 1 250.00 45 Fiction
2 2 States 3 299.00 120 Fiction
3 The White Tiger 2 399.00 35 Fiction
4 Wise and Otherwise 5 199.00 80 Non-Fiction
5 The Immortals of Meluha 4 349.00 65 Fantasy
6 The Blue Umbrella 1 180.00 50 Children
7 Malgudi Days 6 220.00 90 Fiction
8 Train to Pakistan 7 280.00 60 Historical
9 Half Girlfriend 3 280.00 95 Fiction
10 The Palace of Illusions 8 450.00 25 Mythology

(Assume we have 8 authors with IDs 1 to 8)

1. The Main Aggregate Functions

These functions summarize multiple rows into one single value.

Function What it does Ignores NULL? Example Usage
COUNT() Counts number of rows (or non-NULL values) Yes How many books? How many authors?
SUM() Adds up all values Yes Total stock, total revenue
AVG() Average (mean) of values Yes Average book price
MIN() Smallest value Yes Cheapest book
MAX() Largest value Yes Most expensive book

Important: When you use an aggregate function without GROUP BY, it gives one result for the entire table.

Examples (no GROUP BY yet):

SQL

Pro Tip: COUNT(*) counts all rows (including NULLs). COUNT(column) counts only non-NULL values in that column.

2. GROUP BY – Grouping Rows Before Aggregating

This is the game-changer! GROUP BY tells SQL: “Group rows that have the same value in this column, then apply aggregates to each group.”

Syntax:

SQL

Real examples:

SQL

Result might look like:

author_id number_of_books
1 2
2 1
3 2
4 1
5 1
6 1
7 1
8 1
SQL

Even better – join with authors for names:

SQL

Important Rule: Any column in SELECT that is not inside an aggregate function must appear in GROUP BY.

Wrong:

SQL

Correct:

SQL

3. HAVING Clause – Filtering Groups (WHERE for Aggregates)

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

Syntax:

SQL

Examples:

SQL

Result: only author_id 1 and 3 (they have 2 books each)

SQL

Very common pattern – combine WHERE + GROUP BY + HAVING:

SQL

Full Realistic Report Example

SQL

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *