Database Queries: A First Look at SQL · Lesson 29 of 112

Database Aggregates and GROUP BY

What you will learn

  • The aggregate functions COUNT, SUM, AVG, MIN and MAX
  • How GROUP BY makes one summary row per group
  • The difference between WHERE and HAVING
  • How NULL is treated by aggregates

This lesson runs on the sample database you chose in lesson 4.1. Use the Example data picker at the top to change it.

1. Aggregate functions

An aggregate function reads many rows and returns one value.

SELECT COUNT(*) AS orders FROM orders;
SELECT SUM(quantity) AS items FROM order_items;
SELECT MIN(order_date) AS first, MAX(order_date) AS last FROM orders;
SELECT ROUND(AVG(price), 2) AS avg_price FROM products;
orders
------
  2600
(1 row)

items
-----
 9197
(1 row)

first       last
----------  ----------
2024-01-01  2026-09-30
(1 row)

avg_price
---------
    29.16
(1 row)
SELECT COUNT(*) AS ledger_entries FROM transactions;
SELECT SUM(amount_cents) / 100.0 AS total_deposits FROM transactions WHERE kind = 'deposit';
SELECT MIN(txn_date) AS first, MAX(txn_date) AS last FROM transactions;
SELECT ROUND(AVG(balance_cents) / 100.0, 2) AS avg_balance FROM accounts;
ledger_entries
--------------
          7415
(1 row)

total_deposits
--------------
      994418.0
(1 row)

first       last
----------  ----------
2018-02-23  2026-09-30
(1 row)

avg_balance
-----------
     1382.2
(1 row)
SELECT COUNT(*) AS enrollments FROM enrollments;
SELECT SUM(credits) AS total_credits FROM courses;
SELECT MIN(due_date) AS first, MAX(due_date) AS last FROM assignments;
SELECT ROUND(AVG(grade), 1) AS avg_grade FROM enrollments;
enrollments
-----------
       1002
(1 row)

total_credits
-------------
           59
(1 row)

first       last
----------  ----------
2025-02-17  2026-05-03
(1 row)

avg_grade
---------
     71.3
(1 row)
  • COUNT(*) counts rows.
  • SUM adds, AVG averages, MIN and MAX find the smallest and largest (they work on dates and text too).

2. NULL and aggregates

COUNT(column) counts only rows where that column is not NULL, while COUNT(*) counts all rows:

SELECT COUNT(phone) AS with_phone, COUNT(*) AS everyone FROM customers;
with_phone  everyone
----------  --------
       336       420
(1 row)

Customers without a phone number are counted by COUNT(*) but not by COUNT(phone).

SELECT COUNT(note) AS with_note, COUNT(*) AS all_rows FROM audit_log;
with_note  all_rows
---------  --------
       91       120
(1 row)

Audit rows without a note are counted by COUNT(*) but not by COUNT(note).

SELECT COUNT(grade) AS graded, COUNT(*) AS all_rows FROM enrollments;
graded  all_rows
------  --------
   809      1002
(1 row)

Enrollments without a grade yet are counted by COUNT(*) but not by COUNT(grade).

SUM, AVG, MIN and MAX also ignore NULL, which is why the average in lesson 1.1 used only the known ages.

3. GROUP BY

Without groups you get one answer for the whole table. GROUP BY splits the rows into groups first and gives one result row per group:

SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status;
SELECT supplier_id, COUNT(*) AS products, ROUND(AVG(price), 2) AS avg_price FROM products GROUP BY supplier_id ORDER BY supplier_id;
status     orders
---------  ------
cancelled     170
delivered    1878
paid          186
pending       135
shipped       231
(5 rows)

supplier_id  products  avg_price
-----------  --------  ---------
          1         5      28.44
          2         6      29.23
          3         8       24.2
          4         1       29.5
          5         3      35.15
          6         4      37.75
          7         3      51.03
          8         4      14.86
          9         5      27.57
         10         6      27.43
(10 rows)

Customers who never ordered have no rows in orders, so they form no group.

SELECT kind, COUNT(*) AS entries, SUM(amount_cents) / 100.0 AS total FROM transactions GROUP BY kind ORDER BY kind;
SELECT account_type, COUNT(*) AS accounts, ROUND(AVG(balance_cents) / 100.0, 2) AS avg_balance FROM accounts GROUP BY account_type ORDER BY account_type;
kind          entries     total
------------  -------  --------
deposit          3107  994418.0
fee               403    2257.0
interest          308     728.3
transfer_in       539   78918.0
transfer_out      539   78918.0
withdrawal       2519  370898.0
(6 rows)

account_type  accounts  avg_balance
------------  --------  -----------
checking           316      1386.62
savings            134      1371.78
(2 rows)

Each group is one kind of ledger entry, or one type of account.

SELECT term, COUNT(*) AS sections FROM sections GROUP BY term ORDER BY term;
SELECT department_id, COUNT(*) AS courses, SUM(credits) AS credits FROM courses GROUP BY department_id ORDER BY department_id;
term         sections
-----------  --------
2025-Autumn        14
2025-Spring        16
2026-Spring        11
(3 rows)

department_id  courses  credits
-------------  -------  -------
            1        3       11
            2        4       15
            3        3        8
            4        3        8
            5        3        6
            6        3       11
(6 rows)

Each group is one term, or one department.

The rule of thumb: every column in SELECT must either be in GROUP BY or be inside an aggregate function.

4. WHERE versus HAVING

  • WHERE filters rows before they are grouped.
  • HAVING filters groups after they are summed.
SELECT status, COUNT(*) AS orders FROM orders WHERE order_date >= '2026-09-01' GROUP BY status ORDER BY status;
SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id HAVING COUNT(*) >= 10 ORDER BY orders DESC, customer_id LIMIT 5;
status     orders
---------  ------
cancelled       2
delivered      27
paid           17
pending        25
shipped        13
(5 rows)

customer_id  orders
-----------  ------
         72      17
        292      17
        134      15
         42      14
        199      14
(5 rows)

The first query counts only September orders (rows removed before grouping). The second keeps only customers with at least 10 orders (groups removed after counting).

SELECT kind, COUNT(*) AS entries FROM transactions WHERE txn_date >= '2026-01-01' GROUP BY kind ORDER BY kind;
SELECT account_id, COUNT(*) AS entries FROM transactions GROUP BY account_id HAVING COUNT(*) >= 30 ORDER BY entries DESC, account_id LIMIT 5;
kind          entries
------------  -------
deposit           551
fee                84
interest           50
transfer_in       315
transfer_out      315
withdrawal        428
(6 rows)

account_id  entries
----------  -------
        24       37
       254       37
       387       36
        39       35
       165       33
(5 rows)

The first query counts only entries from 2026 on (rows removed before grouping). The second keeps only accounts with at least 30 ledger entries (groups removed after counting).

SELECT course_id, COUNT(*) AS sections FROM sections WHERE term = '2025-Spring' GROUP BY course_id ORDER BY course_id LIMIT 5;
SELECT section_id, COUNT(*) AS students FROM enrollments GROUP BY section_id HAVING COUNT(*) >= 30 ORDER BY students DESC, section_id LIMIT 5;
course_id  sections
---------  --------
        2         1
        3         1
        4         1
        5         1
        6         1
(5 rows)

section_id  students
----------  --------
        31        34
        34        34
        33        33
         5        32
        15        32
(5 rows)

The first query looks only at 2025-Spring sections (rows removed before grouping). The second keeps only sections with at least 30 students (groups removed after counting).

You cannot use an aggregate such as COUNT(*) or SUM(...) in WHERE; that is what HAVING is for.

5. A trap in SQLite

What if you select a column that is neither grouped nor aggregated?

SELECT customer_id, order_date, COUNT(*) AS orders FROM orders GROUP BY customer_id ORDER BY customer_id LIMIT 4;
customer_id  order_date  orders
-----------  ----------  ------
          1  2025-10-01       9
          2  2026-01-04       6
          3  2025-10-17       6
          4  2024-06-10       5
(4 rows)
SELECT account_id, txn_date, COUNT(*) AS entries FROM transactions GROUP BY account_id ORDER BY account_id LIMIT 4;
account_id  txn_date    entries
----------  ----------  -------
         1  2025-05-27       24
         2  2021-11-26       10
         3  2024-09-03       28
         4  2023-05-04       13
(4 rows)
SELECT student_id, enrolled_on, COUNT(*) AS sections FROM enrollments GROUP BY student_id ORDER BY student_id LIMIT 4;
student_id  enrolled_on  sections
----------  -----------  --------
         1  2026-01-18          3
         2  2026-01-16          5
         3  2025-08-10          4
         4  2025-01-21          2
(4 rows)

SQLite does not stop you: it picks the date from one row in each group. A group with several rows has several dates, so a single date makes no sense. The answer looks valid but is not meaningful, so follow the rule of thumb above. Which row SQLite picks is not defined, so another version of SQLite may show a different date than the one printed here. (Do not assume other systems behave the same; check the documentation of the one you use.)

Worked example: which group is the biggest?

How many products does each supplier provide, and what is the cheapest product of each?

SELECT supplier_id, COUNT(*) AS products, MIN(price) AS cheapest FROM products GROUP BY supplier_id ORDER BY products DESC, supplier_id LIMIT 5;
supplier_id  products  cheapest
-----------  --------  --------
          3         8       8.5
          2         6       4.5
         10         6      4.95
          1         5       8.5
          9         5       6.6
(5 rows)

How many ledger entries are there of each kind, and what is the biggest amount of each?

SELECT kind, COUNT(*) AS entries, MAX(amount_cents) AS biggest FROM transactions GROUP BY kind ORDER BY entries DESC, kind;
kind          entries  biggest
------------  -------  -------
deposit          3107    80000
withdrawal       2519    30000
transfer_in       539    29700
transfer_out      539    29700
fee               403     1000
interest          308      876
(6 rows)

How many courses does each department have, and what is the most credits of any of its courses?

SELECT department_id, COUNT(*) AS courses, MAX(credits) AS most_credits FROM courses GROUP BY department_id ORDER BY courses DESC, department_id;
department_id  courses  most_credits
-------------  -------  ------------
            2        4             4
            1        3             4
            3        3             3
            4        3             3
            5        3             2
            6        3             4
(6 rows)

GROUP BY makes one row per group, the aggregates summarise each group, and ORDER BY sorts the summary rows. (Names that belong to a group's id come from other tables; joining them is lesson 4.5. All data is made up.)

Common mistakes

  • Using an aggregate in WHERE. Use HAVING.
  • Selecting ungrouped columns. Put them in GROUP BY or aggregate them.
  • Forgetting that COUNT(column) skips NULL. Use COUNT(*) to count rows.
  • Expecting empty groups. A group exists only if at least one row belongs to it.

Key takeaways

  • COUNT, SUM, AVG, MIN, MAX turn many rows into one value.
  • Aggregates ignore NULL; COUNT(*) counts all rows.
  • GROUP BY gives one summary row per group.
  • WHERE filters rows before grouping; HAVING filters groups after.

Practice

1. Write a query for the number of rows in a table.

Show answer

SELECT COUNT(*) FROM products; returns the number of products (45).

Show answer

SELECT COUNT(*) FROM accounts; returns the number of accounts (450).

Show answer

SELECT COUNT(*) FROM students; returns the number of students (360).

2. What is the difference between COUNT(*) and COUNT(column) when the column can be NULL?

Show answer

COUNT(*) counts all rows; COUNT(column) counts only the rows where that column is not NULL.

3. Write a query for the number of rows per group.

Show answer

SELECT status, COUNT(*) FROM orders GROUP BY status; returns the number of orders per status.

Show answer

SELECT status, COUNT(*) FROM accounts GROUP BY status; returns the number of accounts per status.

Show answer

SELECT enrolled_year, COUNT(*) FROM students GROUP BY enrolled_year; returns the number of students per enrollment year.

4. Which of WHERE and HAVING can use SUM(...)?

Show answer

HAVING, because it filters groups after they are summed.

5. Why does a value that has no rows in a table never appear in the result of GROUP BY on that table?

Show answer

A group is made from rows. If no row has that value, there is nothing to form a group, so there is no summary row for it.

6. Why is it a bad idea to select a column that is neither in GROUP BY nor inside an aggregate?

Show answer

A group has several rows and so several values of that column. SQLite picks one of them without telling you which, so the answer looks valid but is not meaningful. Other systems stop with an error.