Find outliers with z-scores
Compute the mean and standard deviation once, then score every row by its distance from the mean in standard deviations.
The task
Percentile outliers show the tails; z-scores quantify how abnormal each tail value is. Anything beyond three standard deviations from the mean total is worth an audit.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
WITH stats AS (
SELECT AVG(total) AS mean_total,
STDDEV(total) AS sd_total
FROM orders
)
SELECT o.id, o.total,
(o.total - s.mean_total) / s.sd_total AS z_score
FROM orders o
CROSS JOIN stats s
WHERE s.sd_total > 0
AND ABS(o.total - s.mean_total) / s.sd_total > 3
ORDER BY z_score DESC;
工作原理
The stats CTE computes the mean and standard deviation over all orders in one pass. CROSS JOIN attaches them to every row, the z-score divides each row's distance from the mean by the deviation, and the WHERE keeps only |z| beyond 3. The sd > 0 guard prevents division by zero on constant columns. The same statement runs on MySQL and Oracle, but STDDEV means different things: PostgreSQL and Oracle return the sample deviation, MySQL the population one. Write STDDEV_SAMP or STDDEV_POP to pin it down. SQL Server spells it STDEV (first variant); SQLite has no standard-deviation function, so compute SQRT(AVG(total * total) - AVG(total) * AVG(total)) yourself.
Variations
SQL Server: STDEV spelling
SQL ServerWITH stats AS (
SELECT AVG(total) AS mean_total, STDEV(total) AS sd_total
FROM orders
)
SELECT o.id, o.total,
(o.total - s.mean_total) / s.sd_total AS z_score
FROM orders o CROSS JOIN stats s
WHERE s.sd_total > 0
AND ABS(o.total - s.mean_total) / s.sd_total > 3;
Looser threshold: 2 standard deviations (PostgreSQL, MySQL, Oracle)
WITH stats AS (
SELECT AVG(total) AS mean_total, STDDEV(total) AS sd_total
FROM orders
)
SELECT o.id, o.total
FROM orders o CROSS JOIN stats s
WHERE s.sd_total > 0
AND ABS(o.total - s.mean_total) / s.sd_total > 2;
Questions that come up
When do z-scores mislead?
When the distribution is heavily skewed, the mean and standard deviation are dragged by the very outliers you are hunting, so mild extremes get missed and wild ones look milder than they are. Skewed money columns are better screened with percentiles; z-scores shine on roughly symmetric data.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.