01 / 21
SUM COUNT / %

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.

SQL

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?".

Ratio
One aggregate divided by another: \(\frac{\text{SUM}(x)}{\text{SUM}(y)}\)
Rate
A count or sum per unit: \(\frac{\text{COUNT}(\ldots)}{n}\)
Percentage
A ratio scaled to 100: \(\frac{\text{part}}{\text{whole}} \times 100\)

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.

Store A Sales: 1,000 Visitors: 50,000 Rate: 2% Store B Sales: 400 Visitors: 4,000 Rate: 10% vs

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.

1
COUNT(*) : total rows in a group
2
SUM(column) : total of a numeric column
3
AVG(column) : arithmetic mean (itself a derived aggregate!)
4
Division operator \(\;/\;\) : combines two aggregates into a ratio or rate

The Core Pattern

The general formula for any derived aggregate in SQL follows this structure:

SELECT group_col, AGG1(numerator_col) / AGG2(denominator_col) AS derived_metric FROM table_name GROUP BY group_col;

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.

\( \frac{\text{SUM}(x)}{0} \)
PostgreSQL ERROR division by zero MySQL NULL silent null SQL Server ERROR Divide by zero

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.

-- Safe ratio: returns NULL if denominator is 0 SELECT department, SUM(revenue) / NULLIF(SUM(costs), 0) AS revenue_per_cost FROM financials GROUP BY department;

Replacing NULL with COALESCE

Sometimes you want a default value instead of NULL. Wrap the entire division in COALESCE to substitute a fallback.

-- Returns 0 instead of NULL when denominator is 0 SELECT region, COALESCE( SUM(returns) * 100.0 / NULLIF(SUM(orders), 0), 0 ) AS return_rate_pct FROM sales GROUP BY region;
1
NULLIF guards against zero denominator
2
COALESCE replaces resulting NULL with your fallback
3
Multiply by 100.0 (not 100) to force decimal division

Step-by-Step Approach

1
Identify the metric: What ratio, rate, or percentage do you need?
2
Write the numerator: Which aggregate function produces the top value?
3
Write the denominator: Which aggregate produces the bottom value?
4
Guard with NULLIF: Wrap denominator: NULLIF(denominator, 0)
5
Force decimal division: Multiply numerator by 1.0 or use CAST
6
Optional COALESCE: Replace NULL with a meaningful default if needed

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.

-- WRONG: integer division truncates SELECT SUM(clicks) / SUM(impressions) AS ctr; -- Result: 0 (truncated from 0.034) -- CORRECT: force decimal with 1.0 multiplier SELECT SUM(clicks) * 1.0 / NULLIF(SUM(impressions), 0) AS ctr; -- Result: 0.034

Example 1: Conversion Rate

Task: For each marketing campaign, compute the conversion rate as a percentage of visitors who purchased.

SELECT campaign_name, COUNT(*) AS total_visitors, SUM(CASE WHEN purchased = 1 THEN 1 ELSE 0 END) AS buyers, SUM(CASE WHEN purchased = 1 THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(*), 0) AS conversion_pct FROM campaign_visits GROUP BY campaign_name;

Example 2: Revenue per Employee

Task: For each department, compute the revenue generated per employee.

SELECT d.dept_name, SUM(s.revenue) AS total_revenue, COUNT(DISTINCT e.emp_id) AS headcount, ROUND( SUM(s.revenue) * 1.0 / NULLIF(COUNT(DISTINCT e.emp_id), 0), 2 ) AS rev_per_emp FROM departments d JOIN employees e ON d.dept_id = e.dept_id JOIN sales s ON e.emp_id = s.emp_id GROUP BY d.dept_name;

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.

SELECT category, COALESCE( SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(*), 0), 0 ) AS return_rate_pct FROM orders GROUP BY category;

Common Mistakes

✕ No Zero Guard
Dividing without NULLIF: query crashes or returns Infinity when a group has zero in the denominator.
✕ Integer Division
Writing \(\text{SUM}(a)/\text{SUM}(b)\) with integer columns: result truncates to 0 instead of a decimal like 0.034.
✕ Wrong Denominator
Using COUNT(*) when you need COUNT(DISTINCT col): inflated denominator from duplicate rows gives an incorrect rate.

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?