← العودة إلى الدورة: SQL and databases from scratch

Aggregations and GROUP BY

الفيديو قريبًا

Until now each row of the result corresponded to a row of the table. But reports usually ask for summaries: how many customers there are, how much was sold in total, what the average price is. That is what aggregate functions are for: they take many rows and return a single value. They are the basis of any data analysis with SQL.

  • COUNT(*): number of rows.
  • COUNT(col): number of rows where col is not NULL.
  • COUNT(DISTINCT col): distinct values.
  • SUM(col), AVG(col): sum and average.
  • MIN(col), MAX(col): smallest and largest.
sql
SELECT COUNT(*)              AS total_customers,
       COUNT(email)          AS with_email,
       COUNT(DISTINCT city)  AS different_cities
FROM customers;

SELECT SUM(stock * price) AS inventory_value,
       ROUND(AVG(price), 2) AS average_price,
       MIN(price) AS cheapest,
       MAX(price) AS most_expensive
FROM products;

Notice the difference between COUNT(*) and COUNT(email): the first counts 8 rows and the second only 7, because it ignores Felipe's NULL. All aggregates except COUNT(*) ignore NULLs. This is a frequent source of confusion with AVG: the average of a column with missing values is computed only with the present ones. Also, aggregate functions cannot be used in WHERE, because WHERE filters rows before grouping; to filter by an aggregated result you use HAVING, which we will see in the next lesson.

GROUP BY: a summary per group

A single total is rarely enough; usually you want a total per category, per customer or per month. GROUP BY splits the rows into groups according to the values of one or more columns and applies the aggregates to each group separately. The result has one row per group. The golden rule: every column in the SELECT that is not inside an aggregate function must appear in the GROUP BY.

sql
-- Products per category and their average price
SELECT category,
       COUNT(*) AS products,
       ROUND(AVG(price), 2) AS avg_price
FROM products
GROUP BY category
ORDER BY products DESC;

-- Revenue per order: quantity * unit price, summed by order
SELECT order_id, SUM(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id
ORDER BY order_id;

The complete logical order is: FROM, WHERE (filters rows), GROUP BY (groups), HAVING (filters groups), SELECT (computes columns), ORDER BY and LIMIT. Understanding this sequence explains almost all errors with aggregates. For example, if you want to exclude cancelled orders before summing, the filter goes in WHERE, not afterwards. And if you group by two columns, you get one group for each distinct combination.

sql
-- Orders per status
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status;

-- Common ERROR: name is neither aggregated nor in GROUP BY
-- SELECT category, name, COUNT(*) FROM products GROUP BY category;
-- PostgreSQL: column "products.name" must appear in the GROUP BY clause

-- Fix: group by both columns, or remove the extra column
SELECT category, COUNT(*) FROM products GROUP BY category;

A useful way to understand GROUP BY is to imagine that the engine deals the rows into piles, one pile for each distinct value of the grouping column, and then computes the aggregate over each pile. If you group by category, there is one pile per category; if you group by category and status, there is one pile for each pair. After grouping you can only show things that are the same for the whole pile (the grouping columns) or summaries of the pile (the aggregates). With that mental picture, the ungrouped column error stops being a mystery.

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →