BBampaa

Lessons › SQL › Chapter 3: Summarising

SQL lesson

GROUP BY

GROUP BY puts rows with the same value together, like every Electronics order. Then SUM or COUNT works out a number for each group. Put the grouping column in SELECT too, so you can see which total belongs to which group.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

One total per group

SELECT category, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category

Result:

categorytotal_revenue
Electronics448.99
Clothing108.25
Home89.95

Step by step

  1. Puts rows with the same category together.
    SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category
  2. The SUM is worked out for each group, not the whole table.
    SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category
  3. Put the GROUP BY column in SELECT too, to see which total is which.
    SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category

Practice

Try each one in your head first, then open the answer.

1. Using orders, find the total revenue for each category.
SELECT category, SUM(revenue) FROM orders GROUP BY category
2. Using store_sales, find the total revenue for each store_id.
SELECT store_id, SUM(revenue) FROM store_sales GROUP BY store_id
3. Using products, count how many products are in each category.
SELECT category, COUNT(*) FROM products GROUP BY category
4. Using reviews, find the average rating for each product_id.
SELECT product_id, AVG(rating) FROM reviews GROUP BY product_id
5. Using employees, find the total salary for each department.
SELECT department, SUM(salary) FROM employees GROUP BY department

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed