MediumSQL challenge #105JOINGROUP BYSUMCOUNT

Find the Top 15 Customers by Lifetime Revenue

Rank customers by total order value and show name, email, order count and amount spent.

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

Solve This SQL Challenge

Why this question comes up

The marketing team is planning a thank-you offer for its best customers and needs a shortlist: who has spent the most over their whole history with the store, and how often they order. A customer with one large order and one with five medium ones can end up side by side, which is why the order count is shown next to the total.

The task

Find the top 15 customers by total lifetime order value. Show their full name, email, number of orders, and total spent.

A correct answer returns 15 rows with 4 columns: full_name, email, order_count, lifetime_value.

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

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
full_nameemailorder_countlifetime_value
Richard Harrisrichard.harris69@gmail.com26674.57
Amanda Davisamanda.davis49@icloud.com34053.3
Michael Cartermichael.carter46@yahoo.com33628.39
Sharon Wrightsharon.wright26@gmail.com22832.03
Laura Mitchelllaura.mitchell4@yahoo.com22765.92

First 5 of 15 rows. This is the output of the model solution on the practice database.

What you practise

  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • 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
  • Building and cutting text values
  • Sorting the result with ORDER BY
  • Returning only the first rows with LIMIT

Hint and approach

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

Show the hint

JOIN users with orders, then GROUP BY user and use SUM(total)

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 orders.user_id = users.id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  3. Group the rows by users.id, so the result has one row for each value.
  4. For each group, compute COUNT(orders.id) and SUM(orders.total).
  5. Build full_name by joining text values with the || operator.
  6. ROUND() trims the calculated figures to a fixed number of decimals.
  7. Sort the result by lifetime_value descending.
  8. Keep only the first 15 rows with LIMIT.
Show the model solution
SELECT u.first_name || ' ' || u.last_name AS full_name,
       u.email,
       COUNT(o.id) AS order_count,
       ROUND(SUM(o.total), 2) AS lifetime_value
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id
ORDER BY lifetime_value DESC
LIMIT 15;

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

The query starts from users and LEFT JOINs orders, so customers who never ordered stay in the result with a count of 0 and a NULL total. COUNT(o.id) is what makes that count 0; COUNT(*) would report 1 for them.

  • 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.
  • 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.
  • String functions. In SQLite and PostgreSQL, joining text with || returns NULL as soon as one of the parts is NULL.

Another way to solve it

Here the orders are totalled per customer first and only then joined to users, so the join touches one row per customer instead of one per order. Because the top 15 all have orders, an inner join gives the same list; the LEFT JOIN in the model solution matters only when you also want customers who never ordered.

Show the alternative query
WITH spend AS (
  SELECT user_id, COUNT(*) AS order_count, ROUND(SUM(total), 2) AS lifetime_value
  FROM orders
  GROUP BY user_id
)
SELECT u.first_name || ' ' || u.last_name AS full_name,
       u.email, s.order_count, s.lifetime_value
FROM spend s
JOIN users u ON u.id = s.user_id
ORDER BY s.lifetime_value DESC
LIMIT 15;

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