01 / 21

Defining & Implementing
Metrics in SQL

Learn to precisely define business metrics and translate them into reliable SQL queries that power dashboards and decision-making.

SQL Data Analytics

What Is a Metric?

A metric is a quantifiable measurement used to track and assess the status of a specific process, behavior, or outcome. In data analytics, metrics answer questions like: "How many?", "How much?", and "At what rate?"

Metric
A single number summarizing an aspect of your data: "Monthly revenue is $42,000."
Dimension
A categorical attribute you group by: region, product, date, or user segment.

Why Precise Definitions Matter

Two analysts asked "What is our churn rate?" can produce completely different numbers if they define "churn" differently. Precise metric definitions prevent confusion and ensure everyone trusts the data.

Analyst A "Churn = no login 30d" Analyst B "Churn = cancelled sub" 12% churn rate 5% churn rate Conflicting Reports!

Anatomy of a Metric Definition

Every well-defined metric has four components. Think of it as a contract between the business and the database:

1. Name
A clear, unambiguous label: "Monthly Active Users" not just "users."
2. Formula
The exact aggregation: \( \text{COUNT}(\text{DISTINCT user\_id}) \).
3. Filters
The WHERE conditions: only events in the last 30 days, only active accounts.
4. Grain
The time period and grouping level: per month, per region, per product.

The Metric-to-SQL Translation Rule

Metric Definition Name: Monthly Revenue Formula: SUM(amount) Filters: status = 'completed' Grain: Per month maps to SQL Query SELECT month, SUM(amount) FROM orders WHERE status = 'completed' GROUP BY month

Core Aggregation Functions

SQL provides a handful of aggregation functions that form the building blocks of every metric:

Function Purpose Example Metric
COUNT(*) Total rows Total orders
COUNT(DISTINCT x) Unique values Unique customers
SUM(x) Total of a column Total revenue
AVG(x) Mean of a column Avg order value
MAX(x) / MIN(x) Extremes Peak daily sales

COUNT vs COUNT DISTINCT

This is the most common source of metric confusion. The difference is whether you count every row or only unique values:

orders table user_id order_id Alice 101 Alice 102 Bob 103 Carol 104 Alice 105 Bob 106 Carol 107 COUNT(*) 7 COUNT(DISTINCT user_id) 3

Step-by-Step: Metric to SQL

1
State the business question. "How many unique users made a purchase each month?"
2
Identify the metric formula. \( \text{COUNT}(\text{DISTINCT user\_id}) \) because we want unique users.
3
Identify the source table and filters. Table: orders. Filter: status = 'completed'.
4
Choose the grain (GROUP BY). We need "each month," so group by DATE_TRUNC('month', order_date).
5
Assemble and validate. Write the query, run it, and verify the output makes sense.

Example 1: Monthly Active Users

SELECT DATE_TRUNC('month', login_date) AS month, COUNT(DISTINCT user_id) AS monthly_active_users FROM logins GROUP BY DATE_TRUNC('month', login_date) ORDER BY month;

Example 2: Average Order Value

SELECT category, ROUND(AVG(amount), 2) AS avg_order_value FROM orders WHERE status = 'completed' GROUP BY category ORDER BY avg_order_value DESC;

Example 3: Conversion Rate

SELECT DATE_TRUNC('week', visit_date) AS week, COUNT(DISTINCT visitor_id) AS total_visitors, COUNT(DISTINCT CASE WHEN purchased = TRUE THEN visitor_id END) AS purchasers, ROUND( 100.0 * COUNT(DISTINCT CASE WHEN purchased = TRUE THEN visitor_id END) / NULLIF(COUNT(DISTINCT visitor_id), 0) , 2) AS conversion_rate FROM visits GROUP BY 1 ORDER BY week;

Guarding Against Division by Zero

Ratio metrics like conversion rate require dividing one count by another. If the denominator is zero, your query will error or return unexpected results.

Dangerous
purchasers / total_visitors crashes when total_visitors = 0.
Safe
purchasers / NULLIF(total_visitors, 0) returns NULL instead of an error.

WHERE vs HAVING

Both filter data, but at different stages of query execution. Using the wrong one changes your metric's meaning.

Raw Rows FROM table WHERE Filter rows GROUP BY Aggregate HAVING Filter groups Before aggregation After aggregation

Conditional Metrics with CASE WHEN

Many real-world metrics require conditional counting: count only rows that meet a specific condition within a broader grouping.

-- Count orders by payment type in one query SELECT DATE_TRUNC('month', order_date) AS month, COUNT(*) AS total_orders, COUNT(CASE WHEN payment = 'credit' THEN 1 END) AS credit_orders, COUNT(CASE WHEN payment = 'cash' THEN 1 END) AS cash_orders FROM orders GROUP BY 1;

Common Mistakes

✕ Forgetting DISTINCT
Using COUNT(user_id) instead of COUNT(DISTINCT user_id) inflates "unique user" metrics by counting duplicates.
✕ WHERE vs HAVING
Filtering on aggregated values in WHERE causes errors. Use HAVING for conditions on SUM, AVG, or COUNT results.
✕ Division by Zero
Computing ratios without NULLIF(denominator, 0) causes query failures on empty groups.
✕ Wrong Grain
Forgetting GROUP BY or grouping at the wrong level produces misleading numbers (one row vs many).
✕ Missing Filters
Including cancelled orders, test accounts, or internal data in production metrics skews results.

Metric Reference Table

Metric SQL Pattern Key Clause
Total Count COUNT(*) GROUP BY
Unique Count COUNT(DISTINCT col) GROUP BY
Sum SUM(col) GROUP BY
Average AVG(col) GROUP BY
Ratio / Rate \( \frac{\text{agg}}{\text{NULLIF}(\text{agg}, 0)} \) CASE WHEN
Conditional Count COUNT(CASE WHEN ...) CASE WHEN
Filtered Groups agg + HAVING HAVING

Question 1 of 5

You want to count the number of unique customers who placed an order. Which SQL expression is correct?

Question 2 of 5

You need to show only product categories where the average price exceeds $50. Which clause should you use?

Question 3 of 5

What does NULLIF(total_visitors, 0) return when total_visitors equals 0?

Question 4 of 5

To compute the percentage of orders paid by credit card safely in a single grouped query, which pattern is most appropriate?

Question 5 of 5

What is the difference in their January revenue figures?