Aggregation intro

Draft

Aggregates reduce many rows into summaries. GROUP BY decides the level of detail: one row for the whole table, or one row per group.

Count and sum

Aggregate functions collapse many rows into one summary row.

SELECT COUNT(*) AS orders, SUM(total_cents) AS revenue_cents
FROM orders;
Loading plan...

Group by city

GROUP BY returns one summary row for each distinct city.

SELECT city, COUNT(*) AS orders, SUM(total_cents) AS revenue_cents
FROM orders
GROUP BY city
ORDER BY city;
Loading plan...

Filter groups

HAVING filters grouped rows after the aggregate has been computed.

SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
HAVING COUNT(*) > 1
ORDER BY status;
Loading plan...

Try Yourself

Loaded Database:aggregation-intro.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Count only the orders whose status is paid.
2.Group orders by status and return the total revenue for each status.

What We Learned

  • COUNTcounts rows or non-NULL values.
  • SUMadds numeric values across a group.
  • GROUP BYcreates one aggregate result per distinct grouping key.
  • HAVINGfilters groups after aggregation.