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

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-2371HoustonCanada2024-04-13active0
2DonnaAdamsdonna.adams52@gmail.com+1-753-780-6670Fort WorthCanada2020-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
1432638.110.253cancelled2024-04-24NULLLos AngelesUSA
2829470.195delivered2024-03-152023-04-09ChicagoUSA
3136683.240.082delivered2023-02-152023-07-10Los AngelesUSA

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
Paul Youngpaul.young40@proton.me415384.26
Joseph Kingjoseph.king44@yahoo.com514593.17
Michael Rodriguezmichael.rodriguez80@gmail.com412059.32
Amanda Davisamanda.davis49@icloud.com311837.52
Laura Martinlaura.martin80@hotmail.com411780.53

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.

Model solution

Checking your session…

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.
Solve This SQL Challenge

Keep learning