# User Spend Audit

> One user. One category. Total spend.

Canonical URL: <https://datadriven.io/problems/user_spend_audit>

Domain: SQL · Difficulty: medium · Seniority: L4

## Problem

Given the username 'john_doe', what's their total spend on Electronics products with a quality rating above 3?

## Worked solution and explanation

### Why this problem exists in real interviews

This tests a three-table join with multiple filter conditions. Interviewers check whether you can chain joins, apply filters at the right level, and compute an aggregate across the filtered result.

---

### Break down the requirements

#### Step 1: Join users to transactions to products

`users -> transactions -> products` chain: match the user by username, their transactions, and the products in each transaction.

#### Step 2: Filter by username, category, and rating

`WHERE u.username = 'john_doe' AND p.category = 'Electronics' AND p.rating > 3` applies all three conditions.

#### Step 3: Sum total spend

`SUM(t.total_amount)` computes the filtered total spend.

---

### The solution

**Three-table join with multi-filter aggregation**

```sql
SELECT SUM(t.total_amount) AS total_spend
FROM users u
JOIN transactions t ON u.user_id = t.user_id
JOIN products p ON t.product_id = p.product_id
WHERE u.username = 'john_doe'
  AND p.category = 'Electronics'
  AND p.rating > 3
```

> **Cost Analysis**
>
> The username filter narrows 10M users to 1 row. The join to transactions finds that user's ~16 transactions on average. The product join and filters further narrow. This is very fast with indexes on `users(username)` and `transactions(user_id)`.

> **Interviewers Watch For**
>
> The join order and filter placement. Starting from the most selective filter (username) and pushing it early in the execution plan is optimal.

> **Common Pitfall**
>
> Using `rating >= 3` instead of `rating > 3`. The prompt says "above 3," which means strictly greater than, not greater than or equal to.

---

## Common follow-up questions

- What if there are multiple users named 'john_doe'? _(Tests whether to filter by user_id instead, or add additional disambiguation.)_
- How would you show the spend breakdown by product? _(Remove the SUM, add GROUP BY p.product_name, and show individual product totals.)_
- What if SUM returns NULL because no transactions match? _(Use COALESCE(SUM(t.total_amount), 0) to return 0 instead of NULL.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/user_spend_audit)
- [SQL Interview Questions](https://datadriven.io/sql-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.