SQL GROUP BY Practice: Sum Customer Orders
Order tables contain one row per purchase, but reports often need one row per customer. GROUP BY collects rows with the same customer value, and SUM combines their amounts. This example uses SQLite in the browser.
Before you start: Tables, INSERT statements and basic SELECT queries.
Your task
Write a query that groups rows by customer and returns SUM(amount), ordered by customer.
Starter code
CREATE TABLE orders (customer TEXT, amount INTEGER);
INSERT INTO orders VALUES ('Asha', 120), ('Ravi', 80), ('Asha', 200);
-- Write your GROUP BY query below.
Expected result
customer | total
Asha | 320
Ravi | 80The SQL console displays rows as a table. Compare column names and values, rather than the exact text spacing shown here.
Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.
Need a hint?
Select customer and SUM(amount) AS total. Group by customer and order the final result by customer.
Show the complete solution and walkthrough
CREATE TABLE orders (customer TEXT, amount INTEGER);
INSERT INTO orders VALUES ('Asha', 120), ('Ravi', 80), ('Asha', 200);
-- Write your GROUP BY query below.
SELECT customer, SUM(amount) AS total
FROM orders
GROUP BY customer
ORDER BY customer;
- Create the sample orders table and insert the three supplied rows. Asha has amounts 120 and 200; Ravi has one amount of 80.
- Group rows by customer so each name has its own aggregation. SUM(amount) produces 320 for Asha and 80 for Ravi.
- Name the aggregated column total with AS. ORDER BY customer makes the display order explicit; GROUP BY alone does not promise sorted output.
A common mistake
SUM(amount) without GROUP BY returns one total for all orders. Selecting unrelated, non-grouped columns can produce ambiguous results.
Try an edge case
With no rows, this grouped query returns no customer rows. SUM ignores NULL amounts; a group containing only NULL amounts has a NULL sum.
Take it one step further
Add another Ravi order and predict the changed total before running. Then add HAVING SUM(amount) > 100 to keep only groups above the threshold.