# Cost Efficiency Ratio

> Dollars in, value out. What's the ratio?

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

Domain: SQL · Difficulty: easy · Seniority: L3

## Problem

The FinOps team is evaluating per-record cost efficiency for EC2. For the 'EC2' service, what is the ratio of total spend to the number of billing records?

## Worked solution and explanation

### Why this problem exists in real interviews

This is a simple filtered aggregation producing a single scalar value. It tests the ability to compute a ratio from aggregates with a WHERE filter.

---

### Break down the requirements

#### Step 1: Filter to EC2 service

`WHERE svc_name = 'EC2'` restricts to the target service.

#### Step 2: Compute ratio

`SUM(amount) / COUNT(*)` gives total spend divided by number of billing records.

---

### The solution

**Filtered ratio computation**

```sql
SELECT SUM(amount) / COUNT(*) AS cost_per_record
FROM cloud_costs
WHERE svc_name = 'EC2'
```

> **Cost Analysis**
>
> Scan of 4M rows filtered to EC2 records. An index on `svc_name` would reduce the scan. Single-row output.

> **Interviewers Watch For**
>
> Whether the candidate guards against division by zero if no EC2 records exist. Adding NULLIF(COUNT(*), 0) is the safe pattern.

> **Common Pitfall**
>
> If there are zero EC2 records, COUNT(*) returns 0 and division by zero occurs. Wrap with NULLIF: `SUM(amount) / NULLIF(COUNT(*), 0)`.

---

## Common follow-up questions

- What is the difference between AVG(amount) and SUM/COUNT? _(They are equivalent for non-NULL values, but AVG skips NULLs while COUNT(*) does not.)_
- How would you compute this for all services at once? _(GROUP BY svc_name instead of WHERE filter.)_
- What if svc_name matching needed to be case-insensitive? _(Tests LOWER(svc_name) = 'ec2' or ILIKE.)_

## Related

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