Before you start
MySQL or a SQL editor that accepts the starter file
The lessons and MySQL Community Edition are free.
- 01
Create the practice table
Use a separate practice database. Leave your real data alone.
Databases and tablesBro CodeTry it
Run the starter file once in an empty practice database. It creates roadmap_orders and adds four made-up orders.
SELECT * FROM roadmap_orders; should show Alice twice, Bob once and Cara once.
See the practice rows
id | customer | total | status 1 | Alice | 40.00 | paid 2 | Bob | 25.00 | paid 3 | Cara | 15.00 | refunded 4 | Alice | 20.00 | paidIf the table already exists, use a new empty practice database. Re-running INSERT by itself will conflict with the primary keys. You do not need to delete an existing table.
- 02
Choose the columns you need
Start with a small result you can read.
SELECT statementsBro CodeTry it
Return customer and total, sorted from the largest total to the smallest.
The totals should appear as 40, 25, 20 and 15.
Check your query
SELECT customer, total FROM roadmap_orders ORDER BY total DESC;DESC sorts from high to low. SQL does not promise a row order unless you ask for one.
- 03
Keep only paid orders
A refunded order should not count as paid revenue.
WHERE clausesBro CodeTry it
Filter on status = 'paid'. Then add a condition for totals of at least 25.
The first query returns orders 1, 2 and 4. The second returns orders 1 and 2.
Check the two conditions
SELECT id, customer, total FROM roadmap_orders WHERE status = 'paid' AND total >= 25 ORDER BY id;AND means both conditions must be true. Use quotes for the text paid, but not for the number 25.
- 04
Work out what each customer spent
One customer can have more than one order.
Aggregate functionsBro CodeTry it
Sum paid revenue, then group it by customer. Sort the customer totals from high to low.
Paid revenue is 85. Alice has 60 and Bob has 25. Cara should not appear.
Check the grouped query
SELECT customer, SUM(total) AS paid_total FROM roadmap_orders WHERE status = 'paid' GROUP BY customer ORDER BY paid_total DESC;WHERE removes refunded orders before GROUP BY combines each customer's remaining rows. SUM(total) adds the money; COUNT(*) counts orders.
Check your result
Write the queries yourself, then compare your results.
- There are four orders in the table.
- There are three paid orders.
- Paid orders total 85. The refunded order is excluded.
- Alice has spent 60 on paid orders. Bob has spent 25.
What to do next
Add a separate customers table when you want names or contact details without repeating them in every order.
Join two tablesPractice by Abdulrhman Sayed. Video lessons belong to the credited creators.
