MediumSQL challenge #170JOINGROUP BY

Count Orders and Payments per User Without Double Counting

Return every user with their number of orders and their number of payments.

The challenge runs on the SQLabHub practice database (SQLite) and uses the users, orders and payments tables. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

The finance team is reconciling orders against payments per customer. A customer with more payments than orders, or orders but no payments, is worth a closer look, so both counts have to be right.

The task

Find total orders and payments per user.

A correct answer returns 150 rows with 3 columns: id, orders, payments.

Tables used in this challenge

users 150 rows

id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · phone TEXT · city TEXT · country TEXT · created_at TEXT · status TEXT · is_premium INTEGER

First 3 rows of the users table
idfirst_namelast_nameemailphonecitycountrycreated_atstatusis_premium
1JenniferTorresjennifer.torres57@icloud.com+1-263-376-2371MontrealCanada2022-07-15active0
2DonnaAdamsdonna.adams52@gmail.com+1-753-780-6670CalgaryCanada2020-09-15inactive0
3KennethYoungkenneth.young94@proton.me+1-440-743-9503AustinUSA2023-09-05active0

orders 200 rows

id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

payments 207 rows

id INTEGER (PK) · order_id INTEGER · user_id INTEGER · amount REAL · method TEXT · status TEXT · paid_at TEXT · transaction_id TEXT

First 3 rows of the payments table
idorder_iduser_idamountmethodstatuspaid_attransaction_id
12810.52Apple Paysuccess2024-03-15TXNPTNV0A8A1
23136181.19Debit Cardsuccess2023-02-15TXNZAMXH61A0
34115114.95Debit Cardsuccess2022-01-10TXN1PVXYJS9D

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
idorderspayments
112
211
300
433
511

First 5 of 150 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.

What you practise

  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Counting different values with COUNT(DISTINCT …)
  • Grouping rows with GROUP BY to get one result row per group
  • Keeping every row of the left table with LEFT JOIN, matched or not

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Two LEFT JOINs multiply rows, so count each side with COUNT(DISTINCT ...)

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the users table.
  2. LEFT JOIN orders on users.id = orders.user_id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  3. LEFT JOIN payments on users.id = payments.user_id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  4. Group the rows by users.id, so the result has one row for each value.
  5. For each group, compute COUNT(DISTINCT orders.id), which counts each different value once and COUNT(DISTINCT payments.id), which counts each different value once.
Show the model solution
SELECT u.id, COUNT(DISTINCT o.id) AS orders, COUNT(DISTINCT p.id) AS payments FROM users u LEFT JOIN orders o ON u.id = o.user_id LEFT JOIN payments p ON u.id = p.user_id GROUP BY u.id;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

Joining users to orders and to payments in one query pairs every order of a user with every payment of that user. A user with 3 orders and 2 payments becomes 6 rows, so COUNT(o.id) would say 6. COUNT(DISTINCT …) on each side counts each order and each payment once.

  • LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
  • COUNT(DISTINCT). After a join, COUNT(*) counts joined rows. Counting the parent entity needs COUNT(DISTINCT its id).
  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.

Another way to solve it

Two scalar subqueries count each table separately, so no row multiplication can happen in the first place. On this data the counts match the COUNT(DISTINCT) version; the comparison shows why counting each child table on its own is the safer default.

Show the alternative query
SELECT u.id,
       (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS orders,
       (SELECT COUNT(*) FROM payments p WHERE p.user_id = u.id) AS payments
FROM users u;

Checked when this page was built: it returns the same rows as the model solution on the practice database.

Solve This SQL Challenge

Keep learning