Lesson 5 of 10

Aggregate functions

Goal

COUNT, SUM and AVG

01

Explanation

Aggregate functions turn many rows into a single value: COUNT counts rows, SUM adds values up, AVG works out the average, and MIN and MAX give you the smallest and largest values. The database computes them right where the data lives, so you don't have to pull a thousand rows into your program just to add them up there.

There's one difference a lot of people forget: COUNT(*) counts every row, while COUNT(rating) counts only the values that aren't NULL. So an order that was never rated is counted by the first and skipped by the second.

The result column is named after the expression itself, like SUM(amount). If you want a clear name that's easy for code to read later, use AS: SUM(amount) AS revenue.

02

Your task

From the orders table, show a single row with orders_count for the number of orders, rated_count for the number of rated orders, revenue for the total of amount, avg_amount for its average, and min_amount and max_amount for the smallest and largest amount.

Checks

6 checks
  1. The columns have the required names
  2. The orders_count column counts every order
  3. The rated_count column skips orders with no rating
  4. The revenue column is the total of the amounts
  5. The avg_amount column is the average, decimals included
  6. The min_amount and max_amount columns hold the smallest and largest amount
Tables in this lesson
CREATE TABLE orders (
  id       INTEGER PRIMARY KEY,
  customer TEXT    NOT NULL,
  city     TEXT    NOT NULL,
  amount   INTEGER NOT NULL,
  rating   INTEGER
);

INSERT INTO orders (customer, city, amount, rating) VALUES
  ('Layan',  'Riyadh', 120, 5),
  ('Khalid', 'Jeddah', 300, 4),
  ('Layan',  'Riyadh',  80, NULL),
  ('Reem',   'Dammam',  45, 3),
  ('Sara',   'Riyadh', 210, 5),
  ('Khalid', 'Jeddah',  50, NULL),
  ('Fahad',  'Jeddah', 150, 2),
  ('Noura',  'Riyadh',  95, 4),
  ('Omar',   'Mecca',  400, NULL),
  ('Layan',  'Riyadh',  35, 4),
  ('Reem',   'Dammam', 130, NULL),
  ('Sara',   'Riyadh',  70, 3);
03

Hints

0/3
query.sql
OutputSQLite (sql.js)

Loading SQLite.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.