Outliers don't announce themselves — they silently corrupt your aggregates and make your reports lie with correct numbers. Learn how to detect and exclude them using standard deviation, IQR, and percentile-based SQL filtering, all inside a single reproducible query.

Your sales dashboard shows an average order value of $847. Your boss wants to know if that number is real or if it's being dragged up by three enterprise clients who each placed $200,000 orders last quarter. Your churn model predicts 90-day engagement, but you later discover that a batch of test accounts generated 50,000 events each, dwarfing every real user. Your inventory report calculates average days-on-shelf, but someone entered "9999" as a placeholder for products without a scan date.
Outliers are everywhere in production data, and they don't announce themselves. They quietly corrupt your aggregates, skew your models, and make your reports lie with mathematically correct numbers. The professional data analyst doesn't just know how to spot them — they know how to filter them out cleanly, defensibly, and entirely inside a single SQL query that can be audited, versioned, and reproduced by anyone who runs it.
By the end of this lesson, you'll be able to do exactly that. We'll build from the conceptual foundation upward: what an outlier actually is from a statistical standpoint, how to compute detection thresholds using SQL aggregates, and how to wire those thresholds into subqueries that filter your main result set without ever leaving the query. We'll cover three distinct outlier-detection strategies, each with its own use case and trade-offs, and we'll look hard at the performance implications of each approach at scale.
What you'll learn:
This lesson assumes you're comfortable with:
SELECT, WHERE, and FROM clauses — if you need a refresher, start with SQL Basics: Master SELECT, FROM, WHERE Clauses and Build Your First QueriesAVG(), COUNT(), STDDEV(), and MAX() with GROUP BY — covered in Master SQL Aggregate Functions: GROUP BY, HAVING, COUNT, SUM, AVGWITH clauses)You don't need a statistics degree. We'll explain every statistical concept from first principles as we need it.
Before writing a single line of SQL, you need to know what you're actually trying to exclude — because "outlier" can mean very different things depending on the business question.
There are fundamentally two types of outliers you'll encounter:
Data quality outliers are values that shouldn't exist: a temperature sensor that read -999 because the hardware disconnected, a user age of 0 left over from a failed form validation, an order total of 9999999 that was a developer's test transaction. These are errors, and you want to exclude them entirely.
Statistical outliers are legitimate values that sit far outside the typical distribution. A hedge fund manager who processes $4,000,000 in monthly transactions is a real customer — they're just so far from your median retail customer that including them in an average makes the average meaningless as a description of your typical user. Whether you exclude these depends on the question: exclude them for a "typical customer" report, include them for a revenue calculation.
The SQL techniques are the same either way. The decision of what to exclude — and how to document it — is a data analysis judgment call that happens before you write the query.
Note
Always log your outlier exclusion logic in a comment inside the query or in a companion data dictionary. When someone runs your report three months from now, they need to know why certain rows don't appear. "We excluded orders more than 3 standard deviations from the mean" is a defensible, reproducible rule. "We removed the weird ones" is not.
The most commonly used outlier detection method in SQL is the mean ± N standard deviations rule. The idea: calculate the average and standard deviation of a column, then exclude any row where the value falls more than N standard deviations away from that average. The typical choice for N is 2 or 3, capturing 95% or 99.7% of a normally distributed dataset respectively.
Most SQL databases support these aggregate functions:
AVG(column) — arithmetic meanSTDDEV(column) or STDDEV_POP(column) — standard deviationSTDDEV_POP divides by N (the whole population)STDDEV_SAMP or STDDEV divides by N-1 (a sample, which is usually what you want)Tip
In most analytical contexts, your table represents a sample of all possible transactions, not the complete universe of all transactions that will ever exist. Use STDDEV_SAMP (or just STDDEV, which is an alias for the sample version in PostgreSQL and MySQL). If your table truly is the complete population — every order ever placed in a closed historical period — use STDDEV_POP. The difference matters more for small datasets; for millions of rows it's negligible.
Let's say you're analyzing a table called orders with these relevant columns:
orders
order_id INTEGER
customer_id INTEGER
order_date DATE
total_amount NUMERIC(10,2)
channel VARCHAR(50)
Your goal: compute the average order value for the current month, excluding statistical outliers.
Step 1: Compute the threshold in a subquery.
SELECT
AVG(total_amount) AS mean_order_value,
STDDEV(total_amount) AS stddev_order_value,
AVG(total_amount) - 3 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 3 * STDDEV(total_amount) AS upper_bound
FROM orders
WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE)
AND order_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month';
Run this first to see what you're working with. Suppose the results are:
| mean_order_value | stddev_order_value | lower_bound | upper_bound |
|---|---|---|---|
| 847.23 | 312.44 | -89.09 | 1783.55 |
Notice the lower bound is negative. Order amounts can't be negative, so you'd clamp that to zero in practice. This is a perfect example of why you inspect the thresholds before blindly filtering.
Step 2: Wire the threshold into a filtering query using a scalar subquery.
SELECT
channel,
COUNT(*) AS order_count,
AVG(total_amount) AS avg_order_value,
MIN(total_amount) AS min_order_value,
MAX(total_amount) AS max_order_value
FROM orders
WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE)
AND order_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month'
AND total_amount BETWEEN
GREATEST(0,
(SELECT AVG(total_amount) - 3 * STDDEV(total_amount)
FROM orders
WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE)
AND order_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month')
)
AND
(SELECT AVG(total_amount) + 3 * STDDEV(total_amount)
FROM orders
WHERE order_date >= DATE_TRUNC('month', CURRENT_DATE)
AND order_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month')
GROUP BY channel
ORDER BY avg_order_value DESC;
This works, but notice the problem: the date filter is repeated three times. That's a maintenance hazard. If a business analyst changes the date range, they have to update it in three places.
Step 3: Refactor with a CTE for sanity.
WITH date_scope AS (
-- Define the time window once so it's easy to change
SELECT
DATE_TRUNC('month', CURRENT_DATE) AS period_start,
DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month' AS period_end
),
thresholds AS (
SELECT
GREATEST(0, AVG(o.total_amount) - 3 * STDDEV(o.total_amount)) AS lower_bound,
AVG(o.total_amount) + 3 * STDDEV(o.total_amount) AS upper_bound
FROM orders o
CROSS JOIN date_scope d
WHERE o.order_date >= d.period_start
AND o.order_date < d.period_end
),
filtered_orders AS (
SELECT o.*
FROM orders o
CROSS JOIN date_scope d
CROSS JOIN thresholds t
WHERE o.order_date >= d.period_start
AND o.order_date < d.period_end
AND o.total_amount BETWEEN t.lower_bound AND t.upper_bound
)
SELECT
channel,
COUNT(*) AS order_count,
AVG(total_amount) AS avg_order_value,
MIN(total_amount) AS min_order_value,
MAX(total_amount) AS max_order_value
FROM filtered_orders
GROUP BY channel
ORDER BY avg_order_value DESC;
The CROSS JOIN on single-row CTEs is a clean idiom for injecting scalar values into a filtering step. date_scope and thresholds each return exactly one row, so the cross join doesn't multiply rows — it just attaches those values to every row in the main table so you can reference them in the WHERE clause.
Warning
The mean ± standard deviation method assumes your data is roughly normally distributed. If your order values are heavily right-skewed — which is very common for revenue data — the standard deviation will be inflated by high-value outliers, making your upper bound higher than it should be and failing to exclude the very rows you're targeting. We'll address this problem head-on in Strategy 2.
There's no universal right answer, but here's a practical guide:
| N | % of normal distribution included | Typical use case |
|---|---|---|
| 2 | ~95.4% | Aggressive filtering, exploratory analysis |
| 2.5 | ~98.8% | Balanced approach for most business reporting |
| 3 | ~99.7% | Conservative filtering, only removing extreme outliers |
| 4+ | ~99.99% | Only removing almost certainly erroneous values |
For business dashboards, 2.5 to 3 standard deviations is the professional default. Document your choice.
The standard deviation is sensitive to the very outliers you're trying to remove. When your data is skewed — which describes almost all real-world revenue, usage, and behavioral datasets — IQR-based filtering is a more robust choice.
The IQR is the range between the 25th percentile (Q1) and the 75th percentile (Q3). The classic Tukey fences define outliers as values below Q1 - 1.5 * IQR or above Q3 + 1.5 * IQR. Using 3.0 instead of 1.5 creates "extreme outlier" fences that are less aggressive.
SQL doesn't have a universal PERCENTILE() function, but most modern databases offer one:
PostgreSQL:
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY column_name)
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY column_name)
MySQL 8+:
-- Use window functions
PERCENTILE_CONT(0.25) OVER (ORDER BY column_name)
-- Or approximate: no ordered-set aggregate, use NTILE workaround
SQL Server:
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY column_name) OVER ()
BigQuery:
APPROX_QUANTILES(column_name, 4)[OFFSET(1)] -- Q1
APPROX_QUANTILES(column_name, 4)[OFFSET(3)] -- Q3
We'll write this lesson's examples in PostgreSQL syntax, but the structure is transferable.
Let's say we're analyzing a user_sessions table:
user_sessions
session_id INTEGER
user_id INTEGER
session_date DATE
event_count INTEGER
session_minutes NUMERIC(8,2)
platform VARCHAR(20)
We want the average session length by platform for the last 30 days, excluding sessions with event counts that are statistical outliers (indicating bots or test accounts).
WITH session_window AS (
-- Rows within the analysis period
SELECT
session_id,
user_id,
platform,
event_count,
session_minutes
FROM user_sessions
WHERE session_date >= CURRENT_DATE - INTERVAL '30 days'
AND session_date < CURRENT_DATE
),
iqr_bounds AS (
-- Compute Q1, Q3, and IQR in a single pass
SELECT
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY event_count) AS q1,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY event_count) AS q3,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY event_count)
- PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY event_count) AS iqr
FROM session_window
),
tukey_fences AS (
-- Standard Tukey fences: Q1 - 1.5*IQR, Q3 + 1.5*IQR
SELECT
GREATEST(0, q1 - 1.5 * iqr) AS lower_fence,
q3 + 1.5 * iqr AS upper_fence
FROM iqr_bounds
),
filtered_sessions AS (
SELECT s.*
FROM session_window s
CROSS JOIN tukey_fences f
WHERE s.event_count BETWEEN f.lower_fence AND f.upper_fence
)
SELECT
platform,
COUNT(*) AS session_count,
AVG(session_minutes) AS avg_session_minutes,
AVG(event_count) AS avg_event_count,
MAX(event_count) AS max_event_count_included
FROM filtered_sessions
GROUP BY platform
ORDER BY avg_session_minutes DESC;
The CTE chain here does real work at every step:
session_window applies the date filter once, reducing the rows that subsequent CTEs need to processiqr_bounds computes the quartiles using PERCENTILE_CONTtukey_fences translates those quartiles into the actual fence valuesfiltered_sessions applies the fence as a range filterSELECT does the grouped aggregation on only the clean dataThis is exactly the kind of query structure described in Advanced Subqueries and CTEs: Mastering Complex SQL Query Architecture — decomposing a multi-step analytical problem into named, readable, testable stages.
Key insight
The IQR method is resistant to influence from extreme values precisely because it's based on the middle 50% of your data. If 10% of your users are bots generating thousands of events, they don't affect where Q1 and Q3 land. With the standard deviation approach, those same bots would inflate STDDEV() and push your upper fence far higher than it should be, letting some of them slip through.
| Situation | Recommended Method |
|---|---|
| Data is roughly bell-shaped (symmetric) | Standard deviation |
| Revenue, duration, count data (right-skewed) | IQR |
| Small dataset (under 100 rows) | Neither — inspect manually |
| Need to explain methodology to a non-technical stakeholder | Standard deviation (more familiar) |
| Regulatory or audit context requiring reproducible statistical method | IQR (more robust, less assumption-dependent) |
Sometimes the cleanest approach is the most direct one: exclude the top X% and bottom Y% of values, full stop. No standard deviations, no quartiles — just "we don't report on the most extreme 1% of orders."
This is called a percentile cutoff or winsorization boundary. It's especially useful when:
Suppose you're building a supplier performance report. You want to analyze delivery lead times, but you want to exclude the top 2% of lead times (which are almost certainly data entry errors — nobody waits 847 days for a standard part order) and the bottom 1% (zero or negative values from erroneous timestamps).
purchase_orders
po_id INTEGER
supplier_id INTEGER
order_date DATE
received_date DATE
lead_time_days INTEGER -- computed at load time
category VARCHAR(50)
unit_cost NUMERIC(10,2)
WITH po_filtered_period AS (
SELECT
po_id,
supplier_id,
category,
lead_time_days,
unit_cost
FROM purchase_orders
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01'
AND lead_time_days IS NOT NULL
),
lead_time_cutoffs AS (
SELECT
PERCENTILE_CONT(0.01) WITHIN GROUP (ORDER BY lead_time_days) AS p01,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY lead_time_days) AS p99
FROM po_filtered_period
),
clean_pos AS (
SELECT p.*
FROM po_filtered_period p
CROSS JOIN lead_time_cutoffs c
WHERE p.lead_time_days >= c.p01
AND p.lead_time_days <= c.p99
)
SELECT
supplier_id,
COUNT(*) AS po_count,
AVG(lead_time_days) AS avg_lead_time_days,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY lead_time_days) AS median_lead_time,
MIN(lead_time_days) AS min_lead_time,
MAX(lead_time_days) AS max_lead_time
FROM clean_pos
GROUP BY supplier_id
ORDER BY avg_lead_time_days;
Notice we're reporting both AVG and MEDIAN (via PERCENTILE_CONT(0.5)) in the final output. Even after filtering, the median is a useful sanity check — if avg_lead_time_days and median_lead_time are far apart within a single supplier, there may still be skew worth investigating.
Tip
Percentile cutoffs have a subtle advantage: they're stable as your data grows. If you add 100,000 more rows, the P1 and P99 cutoffs shift naturally with the new distribution. Standard deviation cutoffs also shift with new data, but they shift in ways that can be hard to predict when outliers are added. Both are dynamic — just be aware that neither gives you a fixed permanent threshold unless you hardcode the computed values.
Real problems often require filtering outliers on more than one dimension simultaneously. An order might have a reasonable total amount but an absurd quantity (200 units of an item normally bought one at a time), or a session might have a reasonable event count but an impossible duration (600 minutes in a session that started on a mobile device).
Here's a pattern for applying independent outlier filters on two columns:
WITH order_data AS (
SELECT
order_id,
customer_id,
channel,
total_amount,
quantity,
unit_price
FROM orders
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01'
),
amount_bounds AS (
SELECT
AVG(total_amount) - 3 * STDDEV(total_amount) AS amount_lower,
AVG(total_amount) + 3 * STDDEV(total_amount) AS amount_upper
FROM order_data
),
quantity_bounds AS (
SELECT
PERCENTILE_CONT(0.01) WITHIN GROUP (ORDER BY quantity) AS qty_lower,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY quantity) AS qty_upper
FROM order_data
),
clean_orders AS (
SELECT o.*
FROM order_data o
CROSS JOIN amount_bounds ab
CROSS JOIN quantity_bounds qb
WHERE o.total_amount BETWEEN ab.amount_lower AND ab.amount_upper
AND o.quantity BETWEEN qb.qty_lower AND qb.qty_upper
)
SELECT
channel,
COUNT(*) AS order_count,
SUM(total_amount) AS total_revenue,
AVG(total_amount) AS avg_order_value,
AVG(quantity) AS avg_quantity
FROM clean_orders
GROUP BY channel
ORDER BY total_revenue DESC;
Using different methods for different columns (standard deviation for dollar amounts, percentile for quantities) is entirely legitimate — it's not mixing apples and oranges, it's choosing the right tool for each variable's distribution.
Warning
When you apply multiple independent outlier filters, you can accidentally exclude a large fraction of your dataset. If 3% of rows are excluded by the amount filter and 3% by the quantity filter, and those populations don't perfectly overlap, you might be excluding 5-6% total. Add a step that counts rows at each stage so you know what percentage of records you're dropping. If you're excluding more than 5-10% of your data, that's a signal worth investigating — either your thresholds are too aggressive, or you have a genuine data quality problem that needs attention upstream.
There are situations where you don't want to exclude outliers from the dataset — you want to mark them so a downstream query or report can handle them differently. This is especially common when building data marts or staging tables.
The Writing SQL CASE Expressions: Conditional Logic Inside SELECT, WHERE, and GROUP BY technique is perfect here:
WITH thresholds AS (
SELECT
AVG(total_amount) - 2.5 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 2.5 * STDDEV(total_amount) AS upper_bound,
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY total_amount) AS q1,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY total_amount) AS q3
FROM orders
WHERE order_date >= '2024-01-01'
),
labeled_orders AS (
SELECT
o.*,
t.lower_bound,
t.upper_bound,
CASE
WHEN o.total_amount < t.lower_bound
THEN 'low_outlier'
WHEN o.total_amount > t.upper_bound
THEN 'high_outlier'
ELSE 'normal'
END AS amount_outlier_flag,
CASE
WHEN o.total_amount < t.lower_bound OR o.total_amount > t.upper_bound
THEN TRUE
ELSE FALSE
END AS is_amount_outlier
FROM orders o
CROSS JOIN thresholds t
WHERE o.order_date >= '2024-01-01'
)
SELECT
amount_outlier_flag,
COUNT(*) AS record_count,
AVG(total_amount) AS avg_amount,
MIN(total_amount) AS min_amount,
MAX(total_amount) AS max_amount
FROM labeled_orders
GROUP BY amount_outlier_flag
ORDER BY amount_outlier_flag;
This query gives you a distribution report: how many orders fall in each category, and what their amounts look like. Run this before you decide what to exclude. The count and percentage of outliers is itself a diagnostic signal.
The CTE-based patterns above look clean, but they have real performance implications at scale. Let's be specific about what happens under the hood.
In PostgreSQL prior to version 12, CTEs were optimization fences — the query planner could not push predicates through them or merge them with the outer query. Each CTE was materialized as a temporary table. This was often beneficial for the patterns in this article because the threshold subqueries run once and their results are reused.
In PostgreSQL 12+, the planner may choose to inline CTEs rather than materialize them. For outlier detection patterns, you usually want materialization — you're computing the threshold once and referencing it multiple times. Force it explicitly:
-- PostgreSQL 12+ syntax to force materialization
WITH thresholds AS MATERIALIZED (
SELECT
AVG(total_amount) - 3 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 3 * STDDEV(total_amount) AS upper_bound
FROM orders
WHERE order_date >= '2024-01-01'
)
...
Tip
In databases where you can't force CTE materialization (like older MySQL or SQLite), you can achieve the same effect by wrapping your threshold subquery in a JOIN to a derived table. The derived table is always evaluated independently before the join.
Every approach in this article requires at least two passes over your data: one to compute the threshold, one to filter using it. On large tables, this can be expensive.
Option A: Approximate statistics on a sample
If your table has 500 million rows, computing exact quartiles is slow. Consider using a statistical sample for the threshold computation:
WITH thresholds AS (
SELECT
AVG(total_amount) - 3 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 3 * STDDEV(total_amount) AS upper_bound
FROM orders
WHERE order_date >= '2024-01-01'
-- Use TABLESAMPLE for approximate statistics on huge tables
-- PostgreSQL syntax:
-- TABLESAMPLE BERNOULLI(10) -- sample 10% of rows
)
...
Or in BigQuery, use APPROX_QUANTILES() which is designed for fast approximate quantile computation on very large datasets.
Option B: Pre-compute and store thresholds
For daily reporting jobs, consider computing thresholds in a separate step and storing them in a small lookup table:
-- Run once per day as a scheduled job
INSERT INTO reporting.outlier_thresholds (metric, period, lower_bound, upper_bound, computed_at)
SELECT
'order_amount' AS metric,
DATE_TRUNC('day', NOW()) AS period,
AVG(total_amount) - 3 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 3 * STDDEV(total_amount) AS upper_bound,
NOW() AS computed_at
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days';
Then your reporting query joins to this table instead of recomputing. This is especially useful when the same thresholds power multiple reports.
Option C: Indexing strategy
If you're filtering on a column using a computed range (between a lower and upper bound), a standard B-tree index on that column will help the database skip rows outside the range efficiently — but only after the bounds are known. The index can't help with the threshold computation itself.
For the most common pattern — filtering by date AND by an outlier-excluded metric — a composite index on (order_date, total_amount) lets the database scan only the date-relevant partition and then apply the range filter with minimal heap access. See SQL Indexes Explained: How They Work and When to Create Them for the full story on index design.
Everything above computes global thresholds across the entire dataset. But what if you want to detect outliers within each category? A $5,000 order might be normal for enterprise customers but a clear outlier among individual consumers. A 90-minute session might be normal for desktop users but suspicious for mobile.
This requires computing thresholds per group and joining them back. Here's the pattern:
WITH order_data AS (
SELECT
order_id,
customer_id,
customer_tier,
total_amount,
channel
FROM orders
WHERE order_date >= '2024-01-01'
),
tier_thresholds AS (
-- Compute mean and stddev separately for each customer_tier
SELECT
customer_tier,
AVG(total_amount) - 3 * STDDEV(total_amount) AS lower_bound,
AVG(total_amount) + 3 * STDDEV(total_amount) AS upper_bound
FROM order_data
GROUP BY customer_tier
),
clean_orders AS (
SELECT o.*
FROM order_data o
-- Join to get the threshold for THIS order's customer_tier
JOIN tier_thresholds t ON o.customer_tier = t.customer_tier
WHERE o.total_amount BETWEEN t.lower_bound AND t.upper_bound
)
SELECT
customer_tier,
channel,
COUNT(*) AS order_count,
AVG(total_amount) AS avg_order_value
FROM clean_orders
GROUP BY customer_tier, channel
ORDER BY customer_tier, avg_order_value DESC;
The critical move here is the JOIN tier_thresholds t ON o.customer_tier = t.customer_tier. Instead of a CROSS JOIN to a single-row threshold, you join on the grouping key to get the right threshold for each row. This is a powerful pattern for heterogeneous datasets where different segments have fundamentally different distributions.
Key insight
Per-group outlier detection is almost always more analytically defensible than global outlier detection, but it requires more data per group to be statistically meaningful. If a customer tier has only 15 orders, standard deviation-based outlier detection on those 15 numbers is unreliable. Build in a guard: only apply the outlier filter to groups with enough data, and use a simple fixed range for small groups.
Here's how to add that guard:
tier_thresholds AS (
SELECT
customer_tier,
COUNT(*) AS tier_count,
CASE
WHEN COUNT(*) >= 30
THEN AVG(total_amount) - 3 * STDDEV(total_amount)
ELSE NULL -- NULL will cause the BETWEEN to fail safely
END AS lower_bound,
CASE
WHEN COUNT(*) >= 30
THEN AVG(total_amount) + 3 * STDDEV(total_amount)
ELSE NULL
END AS upper_bound
FROM order_data
GROUP BY customer_tier
),
clean_orders AS (
SELECT o.*
FROM order_data o
JOIN tier_thresholds t ON o.customer_tier = t.customer_tier
WHERE (
-- If we have enough data, apply the statistical filter
(t.lower_bound IS NOT NULL AND o.total_amount BETWEEN t.lower_bound AND t.upper_bound)
OR
-- If not enough data, include all rows for this tier
t.lower_bound IS NULL
)
)
The NULL trick here is intentional: x BETWEEN NULL AND NULL evaluates to NULL (not TRUE), which a WHERE clause treats as false. So we explicitly handle the small-group case with the OR branch.
You have a customer_transactions table with the following schema:
customer_transactions
transaction_id INTEGER PRIMARY KEY
customer_id INTEGER
transaction_date DATE
amount NUMERIC(12,2)
merchant_category VARCHAR(50)
country_code CHAR(2)
Your task:
Build a single query (using CTEs) that:
amount columnmerchant_category:Hints:
CASE WHEN inside COUNT() and SUM()Solution:
WITH transactions_2024 AS (
SELECT
transaction_id,
customer_id,
merchant_category,
country_code,
amount
FROM customer_transactions
WHERE transaction_date >= '2024-01-01'
AND transaction_date < '2025-01-01'
),
iqr_stats AS (
SELECT
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY amount) AS q1,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY amount) AS q3,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY amount)
- PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY amount) AS iqr
FROM transactions_2024
),
fences AS (
SELECT
GREATEST(0, q1 - 1.5 * iqr) AS lower_fence,
q3 + 1.5 * iqr AS upper_fence
FROM iqr_stats
),
labeled AS (
SELECT
t.*,
CASE
WHEN t.amount < f.lower_fence OR t.amount > f.upper_fence
THEN TRUE
ELSE FALSE
END AS is_outlier
FROM transactions_2024 t
CROSS JOIN fences f
)
SELECT
merchant_category,
COUNT(*) FILTER (WHERE NOT is_outlier) AS clean_transaction_count,
COUNT(*) FILTER (WHERE is_outlier) AS outlier_count,
SUM(amount) FILTER (WHERE NOT is_outlier) AS total_clean_amount,
AVG(amount) FILTER (WHERE NOT is_outlier) AS avg_clean_amount
FROM labeled
GROUP BY merchant_category
HAVING COUNT(*) FILTER (WHERE NOT is_outlier) >= 100
ORDER BY total_clean_amount DESC;
Note
The FILTER (WHERE ...) syntax is PostgreSQL-specific and extremely useful here. In databases without it (MySQL, older SQL Server), you'd use SUM(CASE WHEN NOT is_outlier THEN amount ELSE 0 END) and COUNT(CASE WHEN NOT is_outlier THEN 1 END) instead.
This is subtle and common. You compute your average and standard deviation across all historical data, but your final query only looks at this month's orders. The thresholds don't match the population.
-- WRONG: threshold computed on all time, applied to one month
WHERE total_amount BETWEEN
(SELECT AVG(total_amount) - 3 * STDDEV(total_amount) FROM orders)
AND
(SELECT AVG(total_amount) + 3 * STDDEV(total_amount) FROM orders)
AND order_date >= DATE_TRUNC('month', CURRENT_DATE)
Always apply the same filters inside the threshold subquery that you apply in the outer query. The CTE pattern makes this explicit and hard to get wrong — your first CTE applies all scope filters, and every downstream CTE references that filtered base.
AVG(), STDDEV(), and PERCENTILE_CONT() all skip NULL values automatically. That's usually fine. But if 30% of your total_amount values are NULL (because cancelled orders have no total), your thresholds are computed on only 70% of your rows, and the filtering behavior in the outer query may be surprising. Always check:
SELECT
COUNT(*) AS total_rows,
COUNT(total_amount) AS non_null_amount_rows,
COUNT(*) - COUNT(total_amount) AS null_amount_rows
FROM orders
WHERE order_date >= '2024-01-01';
If you have a meaningful null rate, decide explicitly: are nulls included in your analysis or not? Filter them out early in your base CTE if not. The NULL Handling in SQL: IS NULL, COALESCE, and NULLIF lesson covers this terrain thoroughly.
You're grouping by product_category and filtering outliers based on unit_price. But unit_price varies dramatically by category — a $2,000 price is an outlier for snacks but completely normal for electronics. If you apply a global IQR filter on unit_price, you'll systematically exclude entire legitimate price tiers for certain categories.
The fix: either use per-group outlier detection (as shown earlier), or only filter on a measure that's comparable across groups (like a normalized metric or a percentage deviation from category mean).
We covered this briefly earlier but it's worth emphasizing. When standard deviation is large relative to the mean (which happens with skewed data), AVG - 3 * STDDEV goes negative. If your column represents money, time, or counts — values that can't be negative — always clamp the lower bound:
GREATEST(0, AVG(amount) - 3 * STDDEV(amount)) AS lower_bound
For IQR fences, the same issue can arise: q1 - 1.5 * iqr can go negative. Apply GREATEST(0, ...) there too.
Standard deviation creates symmetric bounds: N standard deviations above and below the mean. But real-world distributions are often one-sided. For transaction amounts, there's a hard floor at zero but no ceiling. Consider using an asymmetric approach: a 1% lower cutoff and a 99% upper cutoff via percentiles, which naturally adapts to the actual shape of your distribution.
It's tempting to compute daily totals first, then run outlier detection on the daily totals. That's a different and usually wrong analysis — you're detecting outlier days rather than outlier transactions. Be explicit about the grain at which outlier detection operates.
-- This detects outlier transactions (almost always what you want)
WITH thresholds AS (
SELECT AVG(amount) + 3 * STDDEV(amount) AS upper_bound FROM orders
)
SELECT channel, AVG(amount) FROM orders
CROSS JOIN thresholds
WHERE amount <= upper_bound
GROUP BY channel;
-- This detects outlier days (sometimes useful, often wrong for the stated goal)
WITH daily_totals AS (
SELECT order_date, SUM(amount) AS daily_total FROM orders GROUP BY order_date
),
thresholds AS (
SELECT AVG(daily_total) + 3 * STDDEV(daily_total) AS upper_bound FROM daily_totals
)
SELECT order_date, daily_total FROM daily_totals
CROSS JOIN thresholds
WHERE daily_total <= upper_bound;
You can now do something that separates competent SQL writers from genuinely skilled analysts: reason about data quality at the query level and implement that reasoning as defensible, reproducible filtering logic inside a single query.
Here's what you've built:
Three complete outlier detection strategies:
A repeatable query structure:
CROSS JOIN or JOIN in a filtering CTESELECTThe professional discipline around it:
Where to go from here:
The natural next step is making these queries operational — either as views, stored procedures, or scheduled jobs that pre-compute thresholds. If you're building production data pipelines, explore how Writing Multi-Step Analytical Queries: Chaining Subqueries, JOINs, and GROUP BY to Answer Real Business Questions handles the kind of multi-step complexity you've now mastered.
For analysts moving toward window functions and more advanced statistical SQL — Z-scores computed row-by-row, rolling standard deviations, percentile ranks — the techniques in Advanced Subqueries and CTEs: Mastering Complex SQL Query Architecture build directly on the foundation you've developed here.
Outlier handling is never just a SQL problem — it's a data quality judgment call that happens to be implemented in SQL. The queries you write should be explicit enough that someone reading them three months from now understands exactly what was excluded and why. Write that query, and you've written something worth running.
SQL Fundamentals