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