Free courses in AI, Data Science & Machine Learning Written lessons · Quizzes · Final exams
Future Data Academy
Log inGet started ↗
← SQL learning path
Beginner · SQLITE

Grouping and aggregates

Summarise at the right grain.

Understand the concept

GROUP BY changes output grain. COUNT(*) counts rows, COUNT(amount) counts known values, and COUNT(DISTINCT customer_id) counts distinct known identifiers. Group by identity when names are not unique.

Apply the method

WHERE filters input rows; HAVING filters groups. For customers with paid revenue above a threshold, first keep paid orders, then group by customer, then apply HAVING SUM(amount) > threshold.

Avoid a common mistake

SUM and AVG ignore NULL inputs. AVG is not necessarily SUM divided by total row count. Inspect known and missing counts before reporting a mean. A group containing only unknown amounts has an unknown sum, not measured zero.

Worked query

Return customer_count counting all customers.

SELECT COUNT(*) AS customer_count FROM customers;
Run and explore this example →

Check your understanding

Before running your query, predict the output columns and approximate row count. After running it, inspect a missing value, a tie and a record with no match when available. Explain why the result answers the question.

Practice this topic

  1. Customer count — Return customer_count counting all customers.
  2. Missingness audit — Return total_orders and known_amounts: all rows and non-NULL amounts.
  3. Paid revenue — Return revenue as the sum of paid order amounts.
  4. Customers by country — Return country and customers (count), ordered by country.
  5. Average salaries — Return department and avg_salary rounded to two decimals, ignoring unknown salaries, ordered by department.
  6. Repeat orderers — Return customer_id and order_count for customers with at least two orders of any status, ordered by customer_id.
  7. Stock by category — Return category and units as total stock, ordered by category.
  8. Price range summary — Return min_price and max_price across all products.
  9. Orders by status — Return status and orders (count), ordered by status.
  10. High spending customers — Return customer_id and revenue for paid revenue >200, ordered by customer_id.

SQLite reference: SQL language documentation. Written by Future Data Academy with AI assistance; query examples checked against the supplied teaching dataset.