Supplementary project · data analysis

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

Not started

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.

Task 2: customers with at least 200

Guided practice

Task 2: customers with at least 200

Not started

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.

Task 3: revenue per product

Guided practice

Task 3: revenue per product

Not started

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.

Task 4: audit the discrepancy

Guided practice

Task 4: audit the discrepancy

Not started

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.

Task 5: no valid sales

Practice

Task 5: no valid sales

Not started

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.

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_items and products without mixing granularities or duplicating amounts by accident.
  • Calculate metrics with JOIN, GROUP BY, HAVING and aggregate functions.
  • Audit a header total by comparing it with the sum of its lines.
  • Use NOT EXISTS to 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.

Tables you will use
TableWhat a row representsKey relationship
customersA customercustomers.id → orders.customer_id
ordersAn order and its header totalorders.id → order_items.order_id
paymentsA recorded paymentpayments.order_id → orders.id
order_itemsOne line of an orderproduct_id → products.id
productsA productJoined 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

  1. Summarise the amount recorded per payment method and check the overall sum.
  2. Find customers with at least £200 of valid revenue.
  3. Work out which products bring in the most revenue, based on the lines.
  4. Compare each order total with the sum of its lines to find discrepancies.
  5. Find customers with no valid sale and explain why NOT EXISTS suits the question.

Stage 1 · Amount recorded per payment method

Check your understanding

What does a row of the final result represent?

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.

Verified result
methodpaymentsamount
transfer41590,40
card7632,70
paypal4435,90
SQL checked on the teaching database
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

Problem query
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

On your own · aggregation

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.

Stage 3 · Products that bring in the most revenue

On your own · three tables

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.

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.

Audit query, checked
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;
Discrepancy detected
idheader_totallines_total
113Un pago before de agrupar; un método después del summary93,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

Final · applying it

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.

Criteria for considering the project finished

Final self-assessment
CheckYou should be able to explain
GranularityWhy stage 1 starts from one row per recorded payment and stage 3 from one row per line.
FiltersWhy the status is filtered before aggregating.
AggregationWhy the £200 condition uses HAVING.
AuditWhy spotting a difference does not entitle you to choose automatically which total to correct.
AbsenceWhich 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.