Counting and totals

Stage 3: Aggregation · Lesson 10 of 17 · 5 min read · free, interactive

Aggregate functions turn many rows into a single value: COUNT, SUM, AVG, MIN and MAX.

SELECT COUNT(*) AS players, MAX(level) AS top_level FROM players;
SELECT SUM(price) AS total, ROUND(AVG(price), 2) AS average FROM items;

COUNT(*) counts rows. COUNT(column) counts only the rows where that column is not NULL — a handy way to count known values:

SELECT COUNT(*) AS everyone, COUNT(country) AS with_country, COUNT(mentor_id) AS mentored FROM players;

Tip: SUM, AVG, MIN and MAX ignore NULLs too. On an empty table, COUNT returns 0 but SUM and AVG return NULL.

Practice

Each answer runs in your browser and is checked on hidden data.

Previous: Labels with CASE · Next: Groups with GROUP BY · All lessons