SQL project: sales analysis and audit
Answer business questions about a shop, check what each row represents and spot when a JOIN may inflate a metric.
Have a go before opening the examples
First you need: Practice: choose and check a JOIN, Answer questions with subqueries, Find matches with EXISTS, Filter groups with HAVING. If any of the groundwork is missing, go back to that lesson and then carry on from here.
Complete each task, predict a row and explain the decision that produces it. Results are saved per activity.
Guided practice
Task 1: payments by method
Return method, COUNT(*) as payments and ROUND(SUM(pg.amount),2) as amount for payments linked to orders that are not cancelled. Sort by amount DESC and method ASC.
Expected result: 3 rows with the columns method, payments, amount, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Each payment is a row: first decide which payments count (those for orders that are not cancelled).
Join payments to orders on order_id, filter p.status <> 'cancelled' and group by method.
Count with COUNT(*) AS payments, add up with ROUND(SUM(pg.amount),2) AS amount and sort by amount DESC, method.
Solution explained
SELECT pg.method,COUNT(*) AS payments,ROUND(SUM(pg.amount),2) AS amount FROM payments AS pg JOIN orders AS p ON p.id=pg.order_id WHERE p.status <> 'cancelled' GROUP BY pg.method ORDER BY amount DESC,pg.method;An intermediate row represents one payment. In other systems an order can have several payments: that unit must be kept in the definition of the metric.
Task 2: customers with at least 200
Guided practice
Task 2: customers with at least 200
Return name, COUNT(p.id) as orders and ROUND(SUM(p.total),2) as billing for customers whose non-cancelled sum is >= 200. Sort by billing DESC and name ASC.
Expected result: 5 rows with the columns name, orders, billing, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Filter out cancelled orders before grouping, and apply the minimum sum afterwards with HAVING.
Join customers to orders, group by c.id and c.name, and use HAVING SUM(p.total) >= 200.
The aliases are orders and billing; sort by billing DESC and name ASC.
Solution explained
SELECT c.name,COUNT(p.id) AS orders,ROUND(SUM(p.total),2) AS billing FROM customers AS c JOIN orders AS p ON p.customer_id=c.id WHERE p.status <> 'cancelled' GROUP BY c.id,c.name HAVING SUM(p.total)>=200 ORDER BY billing DESC,c.name;Rows are filtered before summarising, and groups afterwards. Each final row represents one customer.
Task 3: revenue per product
Guided practice
Task 3: revenue per product
Return the product name, SUM(quantity) as units and ROUND(SUM(quantity*unit_price),2) as revenue from the lines of orders that are not cancelled. Show the five highest revenues, with name ASC as the tiebreaker.
Expected result: 5 rows with the columns name, units, revenue, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Revenue comes from the lines (quantity × unit_price), not from the order total.
Join order_items to orders (for the status) and to products (for the name), and group by product.
Sort by revenue DESC and name ASC, and limit the result with LIMIT 5.
Solution explained
SELECT pr.name,SUM(d.quantity) AS units,ROUND(SUM(d.quantity*d.unit_price),2) AS revenue FROM order_items AS d JOIN orders AS p ON p.id=d.order_id JOIN products AS pr ON pr.id=d.product_id WHERE p.status <> 'cancelled' GROUP BY pr.id,pr.name ORDER BY revenue DESC,pr.name LIMIT 5;The measure comes from the lines, using their historical price; not from the current price or from the header total repeated on each line.
Task 4: audit the discrepancy
Guided practice
Task 4: audit the discrepancy
Return id, the header total as header_total and ROUND(SUM(quantity*unit_price),2) as lines_total for orders where the absolute difference is greater than 0.001. Sort by id. Find the problem without changing any data.
Expected result: 1 row with the columns id, header_total, lines_total, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
Compare two figures for the same order: the header total and the sum of its lines.
Group by order and compare the two figures with HAVING, using ABS(difference) to ignore the sign.
HAVING ABS(p.total - SUM(d.quantity*d.unit_price)) > 0.001, sorting by p.id.
Solution explained
SELECT p.id,p.total AS header_total,ROUND(SUM(d.quantity*d.unit_price),2) AS lines_total FROM orders AS p JOIN order_items AS d ON d.order_id=p.id GROUP BY p.id,p.total HAVING ABS(p.total-SUM(d.quantity*d.unit_price))>0.001 ORDER BY p.id;Order 113 has 98 in its header and 93.90 in its lines. SQL pinpoints an inconsistency; it does not prove which amount is correct.
Task 5: no valid sales
Practice
Task 5: no valid sales
Return the name of customers with no non-cancelled order at all. Use NOT EXISTS and sort by name.
Expected result: 2 rows with the column name, in that order. Keep the row order requested.
View tables and data
Open this panel to see the full data.
You are not looking for customers with no orders at all, but for those with no order that meets the rule.
The inner query must be linked to the outer customer.
Negate EXISTS for a non-cancelled order.
Solution explained
SELECT c.name FROM customers AS c WHERE NOT EXISTS(SELECT 1 FROM orders AS p WHERE p.customer_id=c.id AND p.status <> 'cancelled') ORDER BY c.name;A customer can have cancelled orders and still have no valid sale under this report's rule.
To finish: explain what a row represents, which requirement you checked and what would change if the rule changed.
See worked examples and checks
By the end, you will be able to
- Turn a sales question into a specific unit of analysis before writing any SQL.
- Combine
customers,orders,payments,order_itemsandproductswithout mixing granularities or duplicating amounts by accident. - Calculate metrics with
JOIN,GROUP BY,HAVINGand aggregate functions. - Audit a header total by comparing it with the sum of its lines.
- Use
NOT EXISTSto find customers with no valid sales under the project's rule.
Before you start: you should be comfortable with JOIN, GROUP BY, HAVING and EXISTS. This project is not one of the 52 core lessons: use it to practise applying what you know.
Scenario and business rule
You are working with the shop's teaching database. Management wants a simple report to review sales and spot inconsistencies before figures are shared. For this project, an order with the status 'cancelled' does not count as a valid sale; that is a rule of the exercise, not a universal SQL rule.
| Table | What a row represents | Key relationship |
|---|---|---|
customers | A customer | customers.id → orders.customer_id |
orders | An order and its header total | orders.id → order_items.order_id |
payments | A recorded payment | payments.order_id → orders.id |
order_items | One line of an order | product_id → products.id |
products | A product | Joined from each line |
Check rule: before aggregating, write one statement describing what a row of your intermediate set represents. If you go from one row per order to one row per line, a header amount can be repeated several times.
Project plan
- Summarise the amount recorded per payment method and check the overall sum.
- Find customers with at least £200 of valid revenue.
- Work out which products bring in the most revenue, based on the lines.
- Compare each order total with the sum of its lines to find discrepancies.
- Find customers with no valid sale and explain why
NOT EXISTSsuits the question.
Stage 1 · Amount recorded per payment method
The 15 rows in payments are summarised into three methods and add up to £2,659.00. That figure matches the sum of the non-cancelled orders in this data set, but do not turn that coincidence into a universal rule: another system might allow partial payments, refunds or several payments per order.
| method | payments | amount |
|---|---|---|
| transfer | 4 | 1590,40 |
| card | 7 | 632,70 |
| paypal | 4 | 435,90 |
SELECT pg.method,
COUNT(*) AS payments,
ROUND(SUM(pg.amount), 2) AS amount
FROM payments AS pg
JOIN orders AS p ON p.id = pg.order_id
WHERE p.status <> 'cancelled'
GROUP BY pg.method
ORDER BY amount DESC, pg.method;Start with a metric from the paymentstable. An intermediate row represents a recorded payment; join orders only to apply the project rule and exclude cancelled orders before grouping by method.
A mistake that can inflate revenue
Adding up the header total after multiplying each order by its lines
SELECT SUM(p.total)
FROM orders AS p
JOIN order_items AS d ON d.order_id = p.id
WHERE p.status <> 'cancelled';If an order has three lines, p.total appears three times in the joined set. The JOIN is not “wrong”: it changed the granularity to one row per line. The mistake is to keep treating p.total as if each order appeared only once.
Stage 2 · Customers with at least £200
Filter after summarising
Return the customers whose non-cancelled revenue is at least £200. Include the name, the number of orders and the revenue, and sort from highest to lowest revenue.
Success criteria: five customers should appear; Sara Green comes first with £1,112.00 and Megan Reed ends the result with £215.90.
WHERE before grouping.SUM(p.total) belongs to HAVING.Solution explained
SELECT c.name,
COUNT(p.id) AS orders,
ROUND(SUM(p.total), 2) AS billing
FROM customers AS c
JOIN orders AS p ON p.customer_id = c.id
WHERE p.status <> 'cancelled'
GROUP BY c.id, c.name
HAVING SUM(p.total) >= 200
ORDER BY billing DESC, c.name;| name | orders | billing |
|---|---|---|
| Sara Green | 2 | 1112,00 |
| Amy Wilson | 2 | 377,40 |
| Hugh Miller | 2 | 268,00 |
| Liam Martin | 2 | 253,40 |
| Megan Reed | 2 | 215,90 |
WHERE decides which orders go into the calculation; HAVING decides which groups survive after the sum.
Stage 3 · Products that bring in the most revenue
Change the unit to the order line
Calculate the units sold and the revenue for each product using quantity * unit_price. Exclude cancelled orders and show the five products with the highest revenue.
Success criteria: Pro Laptop comes first with £999.00; Monitor 24 comes second with 3 units and £537.00.
order_items: one row represents one line.orders to get the status, and products to get the name.SUM(d.quantity) and SUM(d.quantity * d.unit_price).Solution explained
SELECT pr.name,
SUM(d.quantity) AS units,
ROUND(SUM(d.quantity * d.unit_price), 2) AS revenue
FROM order_items AS d
JOIN orders AS p ON p.id = d.order_id
JOIN products AS pr ON pr.id = d.product_id
WHERE p.status <> 'cancelled'
GROUP BY pr.id, pr.name
ORDER BY revenue DESC, pr.name
LIMIT 5;| name | units | revenue |
|---|---|---|
| Pro Laptop | 1 | 999,00 |
| Monitor 24 | 3 | 537,00 |
| SSD drive | 3 | 267,00 |
| Headphones | 4 | 253,70 |
| Monitor 27 | 1 | 249,00 |
Now it does make sense to aggregate line amounts, because each intermediate row represents a line and the calculation uses columns at that same granularity.
Limiting to five rows on each engine: the project query uses LIMIT 5 because the local database runs on SQLite. PostgreSQL and MySQL also accept LIMIT; in SQL Server, use SELECT TOP (5) with the same ORDER BY.
Stage 4 · Audit the header against the lines
The project deliberately contains a discrepancy so you can practise an integrity check. Group the lines by order and compare their sum with orders.total.
SELECT p.id,
p.total AS header_total,
ROUND(SUM(d.quantity * d.unit_price), 2) AS lines_total
FROM orders AS p
JOIN order_items AS d ON d.order_id = p.id
GROUP BY p.id, p.total
HAVING ABS(p.total - SUM(d.quantity * d.unit_price)) > 0.001
ORDER BY p.id;| id | header_total | lines_total |
|---|---|---|
| 113 | Un pago before de agrupar; un método después del summary | 93,90 |
The query finds order 113, whose header says £98.00 while its lines add up to £93.90. SQL lets you pinpoint the difference; it does not tell you which value is correct. Fixing it would require knowing the source system's rule, taxes, discounts or other adjustments that this data set does not model.
Stage 5 · Customers with no valid sales
Express the absence with NOT EXISTS
Find the customers for whom no non-cancelled order exists. Sort the names alphabetically.
Success criteria: the result must contain exactly Miles Lee and Peter Hill.
customers.p.customer_id = c.id.'cancelled'.Solution explained
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS p
WHERE p.customer_id = c.id
AND p.status <> 'cancelled'
)
ORDER BY c.name;| name |
|---|
| Miles Lee |
| Peter Hill |
NOT EXISTS expresses the question directly: it keeps the customer when the subquery does not find a single row that meets the condition.
Criteria for considering the project finished
| Check | You should be able to explain |
|---|---|
| Granularity | Why stage 1 starts from one row per recorded payment and stage 3 from one row per line. |
| Filters | Why the status is filtered before aggregating. |
| Aggregation | Why the £200 condition uses HAVING. |
| Audit | Why spotting a difference does not entitle you to choose automatically which total to correct. |
| Absence | Which row would have to appear in the subquery for a customer to be left out of NOT EXISTS. |
What you have shown
- You can define the unit of analysis before writing the aggregation.
- You can keep header metrics and detail metrics apart.
- You can validate a report with counts and expected results, not just with valid syntax.
- You can spot an inconsistency without inventing an explanation the data does not contain.
- You can answer a question about absence with a correlated subquery.
Next step: change one of the project's rules (for example, include cancelled orders, or measure units instead of revenue) and predict which stages need to change before you edit the SQL.