Computing Derived
Aggregates in SQL
Learn to compute ratios, rates, and percentages from grouped data safely: avoiding division by zero, handling NULLs, and writing clear queries.
What Are Derived Aggregates?
A derived aggregate is a new metric you compute by combining two or more aggregate functions. Instead of just asking "how many?" or "what total?", you ask questions like "what fraction?" or "what average rate?".
Why Derived Aggregates Matter
Raw totals can be misleading. A store with 1000 sales sounds impressive until you learn it took 50,000 visitors. The conversion rate of \(2\%\) tells the real story.
The Building Blocks
Every derived aggregate is built from standard SQL aggregate functions. You already know these: the new skill is combining them with division.
The Core Pattern
The general formula for any derived aggregate in SQL follows this structure:
The Division-by-Zero Problem
When a group has zero in the denominator, SQL databases behave differently: some return an error, others return NULL, and some return Infinity. None of these are useful results.
NULLIF vs CASE
SQL gives you two main tools to guard against division by zero. Both convert a zero denominator into NULL, which makes the whole expression return NULL instead of erroring.
| NULLIF | CASE | |
|---|---|---|
| Syntax | NULLIF(expr, 0) | CASE WHEN expr = 0 THEN NULL ELSE expr END |
| Readability | Concise | Verbose but explicit |
| Flexibility | Only checks one value | Can check multiple conditions |
| Best for | Simple zero-guard | Custom fallback values |
The Safe Division Pattern
Memorize this pattern: wrap the denominator in NULLIF so that zero becomes NULL, and the result gracefully becomes NULL rather than crashing.
Replacing NULL with COALESCE
Sometimes you want a default value instead of NULL. Wrap the entire division in COALESCE to substitute a fallback.
Step-by-Step Approach
The Integer Division Trap
In many SQL engines, dividing two integers truncates the result. \(7 \div 2 = 3\), not \(3.5\). This silently destroys your percentages and rates.
Example 1: Conversion Rate
Task: For each marketing campaign, compute the conversion rate as a percentage of visitors who purchased.
Example 2: Revenue per Employee
Task: For each department, compute the revenue generated per employee.
Example 3: Conditional Ratio
Task: Compute the percentage of orders that were returned, by product category, showing 0 instead of NULL for categories with no orders.
Common Mistakes
Quick Reference Table
| Pattern | SQL Template | Safety |
|---|---|---|
| Ratio | SUM(a) / NULLIF(SUM(b), 0) | NULLIF |
| Percentage | SUM(a) * 100.0 / NULLIF(COUNT(*), 0) | NULLIF + 100.0 |
| Rate with fallback | COALESCE(SUM(a) * 1.0 / NULLIF(SUM(b), 0), 0) | COALESCE + NULLIF |
| Conditional % | SUM(CASE ...) * 100.0 / NULLIF(COUNT(*), 0) | CASE + NULLIF |
| Per-unit rate | SUM(a) * 1.0 / NULLIF(COUNT(DISTINCT b), 0) | DISTINCT + NULLIF |
Question 1 of 5
What does NULLIF(expression, 0) return when expression equals \(0\)?
Question 2 of 5
In PostgreSQL, what happens if you compute
SUM(revenue) / SUM(costs) and SUM(costs) is \(0\)?
Question 3 of 5
You write: SUM(clicks) / SUM(impressions) where both columns are integers. SUM(clicks) is 34 and SUM(impressions) is 1000. What is the result?
Question 4 of 5
Which query correctly computes the return rate percentage with a fallback of 0?
Question 5 of 5
You need revenue per unique customer. Which denominator is correct?