# Department Spend Gap

> Gap between Engineering's and Marketing's biggest single purchase

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

Domain: SQL · Difficulty: easy · Seniority: L3

## Problem

What is the absolute difference between the largest single transaction made by anyone in Engineering and the largest single transaction made by anyone in Marketing?

## Worked solution and explanation

### Why this problem exists in real interviews

This tests cross-department scalar comparison. Computing the max transaction for two specific departments and finding the absolute difference probes subquery and ABS() usage.

---

### Break down the requirements

#### Step 1: Find max transaction per department

Join `transactions` to `employees` on `user_id` to get department. Compute `MAX(total_amount)` for Engineering and Marketing separately.

#### Step 2: Compute absolute difference

`ABS(eng_max - mkt_max)` gives the gap.

---

### The solution

**Cross-department max comparison**

```sql
SELECT ABS(
    (SELECT MAX(t.total_amount)
     FROM transactions t
     JOIN employees e ON t.user_id = e.user_id
     WHERE e.department = 'Engineering')
    -
    (SELECT MAX(t.total_amount)
     FROM transactions t
     JOIN employees e ON t.user_id = e.user_id
     WHERE e.department = 'Marketing')
) AS spend_gap
```

> **Cost Analysis**
>
> Two scans of 100M transactions joined to 25K employees, each filtered to one department. An index on `employees(department, user_id)` and `transactions(user_id)` would help.

> **Interviewers Watch For**
>
> Whether the candidate uses scalar subqueries (clean) vs a CASE-based conditional aggregation (also valid). The scalar approach is more readable for exactly two departments.

> **Common Pitfall**
>
> Forgetting ABS() would give a negative result if Marketing's max exceeds Engineering's. The prompt asks for the absolute difference.

---

## Common follow-up questions

- How would you compute this for all department pairs? _(Tests CROSS JOIN of department-level aggregates.)_
- What if an employee belongs to multiple departments? _(Tests whether the schema allows it and how to handle the join.)_
- What if one department has no transactions? _(The MAX subquery returns NULL, making the ABS expression NULL. Tests COALESCE handling.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/department_spend_gap)
- [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.