BBampaa

Lessons › SQL › Chapter 3: Summarising

SQL lesson

GROUP BY

GROUP BY splits your rows into groups based on a shared value, then runs a calculation.

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

Example

Summarising Retail Orders with GROUP BY

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. Run the query without SUM so you can see what the unfiltered values look like.
    SELECT category, revenue
    FROM orders
    GROUP BY category;
  2. SUM totals the numbers in a column. Works on numeric columns only.
    SELECT category, SUM(revenue)
    FROM orders
    GROUP BY category;
  3. AS gives the SUM result a friendly column name so the output reads cleanly.
    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, write a query to find the total revenue for each category.
SELECT category, SUM(revenue) FROM orders GROUP BY category
2. Using store_sales, write a query to find the total revenue for each sale_id.
SELECT sale_id, SUM(revenue) FROM store_sales GROUP BY sale_id
3. Using products, write a query to find the total price for each product_id.
SELECT product_id, SUM(price) FROM products GROUP BY product_id
4. Using reviews, write a query to find the total rating for each customer_id.
SELECT customer_id, SUM(rating) FROM reviews GROUP BY customer_id
5. Using employees, write a query to find the total salary for each employee_id.
SELECT employee_id, SUM(salary) FROM employees GROUP BY employee_id

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