← All lessons
SQL from zero · Lesson 10 of 10

Counting and totals

So far every query has returned rows from the table. Aggregate functions go the other way: they squash many rows into one answer. COUNT(*) counts rows:

SELECT COUNT(*) AS products
FROM products;
Returns
products
--------
8
(1 row)

With WHERE, the counting happens after the filter, so you count just the rows that pass:

SELECT COUNT(*) AS shipped
FROM orders
WHERE status = 'shipped';
Returns
shipped
-------
8
(1 row)

The others work on a column: SUM adds it up, AVG gives the average, and MIN and MAX the smallest and largest. You can ask for several at once:

SELECT MIN(price) AS cheapest, MAX(price) AS dearest, ROUND(AVG(price), 2) AS average
FROM products;
Returns
cheapest | dearest | average
---------+---------+--------
9.75     | 120     | 41.09
(1 row)

NULLs are skipped. COUNT(*) counts every row, but COUNT(city) counts only the rows where city isn't NULL, and COUNT(DISTINCT city) counts the different values:

SELECT COUNT(*), COUNT(city), COUNT(DISTINCT city)
FROM customers;
Returns
COUNT(*) | COUNT(city) | COUNT(DISTINCT city)
---------+-------------+---------------------
8        | 7           | 3
(1 row)

One thing an aggregate can't do on its own: mix with a plain column. SELECT category, COUNT(*) FROM products asks for one count but also for eight categories. To get a count per category you need GROUP BY, which is where the next course, Combining and summarizing, starts.

You've now met everything most people use SQL for every day: picking columns and rows, sorting, missing values, text, sums, labels and totals. The next course puts tables together with joins and summarises them by group.

Practice

How many customers does the shop have? One number.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

COUNT(*)How many rows.
COUNT(x), COUNT(DISTINCT x)How many non-NULL values; how many different ones.
SUM(x), AVG(x)Total; average (NULLs skipped).
MIN(x), MAX(x)Smallest; largest.
per group?Needs GROUP BY: the next course.

The other AI and data engineering courses