Is this extreme value an error or the most important row in my data?
TL;DR
Difficulty: Advanced
An extreme value is a question, not a verdict.
- Sort it first: impossible (breaks a business rule), implausible (needs a look) or a genuine extreme (often your best customer).
- Check domain rules before any statistic.
- On money, use robust rulers: quartile fences and the median absolute deviation, on the log scale, within sensible groups. z scores fail on skewed and small samples.
- A second column (value against items) tells an error from a big real order.
- Compare each day with the same weekday and the same event last year. A volume drop is a pipeline problem to reconcile, not a value to clean.
- Correct at the source, keep, flag for one analysis or cap for a model. Never delete automatically.
Sort any order table by value and a row will make you stop: thousands of euro, a negative quantity, a date in 1970. Deleting it is tempting and often wrong. This chapter shows how to tell an error from the most important row in your data, with rules, robust statistics, SQL, dbt and Python, all worked through on one invented shop in Limerick.
The row that does not fit
Every data engineer meets this row sooner or later. You sort a table by value, and at the top sits a number that makes you stop. An order worth thousands in a shop where the average basket is €84. A quantity of minus three. An order placed in 1970.
The tempting move is to delete it and get on with the report. The row looks wrong, it spoils the chart, and nobody will miss one order. That move is how businesses lose their best customer from their own numbers, and how real errors stay hidden in the source for years.
This chapter answers one question: is this extreme value an error, or the most important row in my data? You will learn to sort extreme values into three kinds, to find them with domain rules first and statistics second, to pick the right statistical ruler for skewed money data, to spot anomalies in time series without being fooled by the calendar, and to decide what to do with each row without ever deleting one automatically. Every method comes with SQL or Python you can run, and every idea is worked through on the same invented shop.
If you have not read the chapter on data profiling, read it first. Profiling is where you first see the extremes. This chapter is where you decide what they mean.
Meet the example shop and its four strange rows
Shannonside Home is an invented online homeware shop in Limerick (shannonsidehome.example). Niamh owns it. Callum is her developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL, sells about 1,400 products and takes about 1,980 orders a month at an average order value (AOV) of €84 including VAT. It has five years of order history, part of it imported from an older platform. Callum loads everything into BigQuery and transforms it with dbt Core.
Example: four rows from one Monday morning
Callum runs his weekly profiling query on spree_orders and spree_line_items and sorts by order total. Four rows catch his eye (all invented):
| Order | Completed | Items | Total | What it looks like |
|---|---|---|---|---|
| R482913 | 6 October 2026, 2.41pm | 400 | €4,620.00 | Someone bought 400 towels |
| L102877 | 14 March 2022, 11.05am | 1 | €7,560.00 | One rug for the price of a car |
| L000412 | 1 January 1970, 00:00 | 2 | €68.00 | An order 52 years before the shop existed |
| L001907 | 9 June 2022, 4.12pm | line quantity minus 3 | €0.00 | A negative number of cushions |
Four rows, four different stories. The rest of this chapter takes each one apart. By the end, one of them will be the most valuable customer of the quarter, two will be errors to fix at the source, and one will be a loading fault that never belonged in the table at all.
Three kinds of extreme value
Before any statistics, give each extreme value a name. There are three kinds, and the kind decides what you are allowed to do with it.
- Impossible values cannot be true in the real world, whatever the context. A negative quantity on a sale. An order completed before the shop opened. A delivery date before the order date. A product weighing minus 2 kg. No statistic is needed to judge them: a rule from the business says no.
- Implausible values could be true but are unlikely enough that a person should look. An order of 400 items. A rug 2,000 cm long. A single order worth 90 times the average. Some will be errors, some will be real.
- Genuine extremes are true, rare and often the most important rows in the table. A hotel furnishing 200 rooms. The first day of a viral product. Black Friday.
The statistician Douglas Hawkins described an outlier as an observation that differs so much from the others that it raises the suspicion it was produced by a different mechanism1. That wording is useful because it does not say "error". A different mechanism can be a typing mistake, a broken import, or a hotel buyer instead of a household. Your job is to find out which mechanism produced the row.
One more distinction runs through the whole chapter. An outlier is one value that sits far from the other values in a column. An anomaly is a broader word for any pattern that breaks expectations, including a whole day with too few rows. A single huge order is an outlier in a value. A Tuesday with a third of the usual orders is an anomaly in volume. They need different detectors and, as you will see, very different fixes.
Example: Callum names the four rows
Callum adds one column to his notes, the kind:
| Order | Kind | Why |
|---|---|---|
| R482913 (400 items, €4,620) | Implausible | Possible for a business buyer, rare for a household |
| L102877 (one rug, €7,560) | Implausible | The most expensive rug in the catalogue costs €749 |
| L000412 (1 January 1970) | Impossible | Shannonside Home took its first order on 4 January 2022 |
| L001907 (quantity minus 3) | Impossible | A sale cannot ship a negative number of items |
Notice what he did not do. He did not compute a single average or standard deviation. Two of the four rows are settled by facts about the business, and those facts are stronger than any statistic.
Domain rules come before statistics
A domain rule is a check written from knowledge of the business: what the shop sells, when it opened, what a quantity can be. It needs no distribution and no threshold to tune. It is also easy to explain to Niamh: "an order cannot be completed before the shop opened" needs no maths.
Statistics answer a different question: is this value unusual compared with the others? That is weaker. An impossible value can look perfectly ordinary to a statistic (the 1970 order is worth €68, right in the middle of the pack), and a genuine extreme can look wildly unusual. So the order is fixed: rules first, statistics second, and statistics only on the rows that pass the rules.
Good domain rules for an online shop fall into four groups:
| Group | Rule | Kind if broken |
|---|---|---|
| Range | Quantity at least 1 on a sold line, price at least 0, weight above 0 | Impossible |
| Time | Completed on or after the first trading day, not in the future | Impossible |
| Cross field | Shipped after completed, refunded amount not above the amount paid | Impossible |
| Plausibility | Line quantity above 50, order above €2,500, rug longer than 600 cm | Implausible, needs review |
The plausibility thresholds come from Niamh, not from a formula. She knows the largest rug she stocks and what a big household order looks like. Write each rule down with its owner and reason, as the chapter on when to clean data and when to leave it alone describes for the rule register.
A word of warning about cross field rules. Some "impossible" values are really standardisation problems. The 3PL warehouse sends time stamps in Irish local time without a zone, while the shop stores UTC. In summer, a return logged at 10.30am local time is 9.30am UTC, so a naive comparison can show a return processed an hour before the parcel was scanned in. That is not an outlier. It is a time zone error, and the fix belongs in standardising values, before any outlier check runs.
Example: the impossible value checks at Shannonside Home
Callum writes the rules as one PostgreSQL query against the shop database. The Solidus tables hold the order total on spree_orders.total, the number of items on spree_orders.item_count, and each line's quantity and price on spree_line_items.
-- PostgreSQL: impossible and implausible values in completed orders
-- completed_at is stored in UTC without a zone, so compare with a UTC literal
select o.number, o.completed_at, o.total, o.item_count,
'impossible: completed before first trading day' as finding
from spree_orders o
where o.state = 'complete'
and o.completed_at < timestamp '2022-01-04 00:00:00'
union all
select o.number, o.completed_at, o.total, o.item_count,
'impossible: line quantity below 1'
from spree_orders o
join spree_line_items li on li.order_id = o.id
where o.state = 'complete'
and li.quantity < 1
union all
select o.number, o.completed_at, o.total, o.item_count,
'implausible: review (over 50 of one item or over 2500 euro)'
from spree_orders o
where o.state = 'complete'
and (o.total > 2500
or exists (select 1 from spree_line_items li
where li.order_id = o.id and li.quantity > 50))
order by finding, completed_at;
Each part of the union all is one rule with its own label, so the output says which rule fired. The result on the invented data:
| number | completed_at | total | item_count | finding |
|---|---|---|---|---|
| L000412 | 1970-01-01 00:00:00 | 68.00 | 2 | impossible: completed before first trading day |
| L001907 | 2022-06-09 16:12:00 | 0.00 | 0 | impossible: line quantity below 1 |
| L102877 | 2022-03-14 11:05:00 | 7560.00 | 1 | implausible: review (over 50 of one item or over 2500 euro) |
| R482913 | 2026-10-06 14:41:00 | 4620.00 | 400 | implausible: review (over 50 of one item or over 2500 euro) |
Both impossible rows carry the prefix L, which in this invented history marks orders imported from the old platform. That is the first clue: the import, not the customers, produced them. A date of 1 January 1970 at midnight is the classic sign of an empty date converted to the Unix epoch, the zero point many systems count time from. Callum now knows where to look, and no statistic told him.
Tukey fences: the interquartile range as a ruler
Once the rules are done, statistics can help find values that are unusual for this data. The oldest robust tool is the box plot rule from John Tukey's work on exploratory data analysis2. It uses quartiles, which are robust: a few extreme values barely move them.
The first quartile is the value below which a quarter of the data lies. The third quartile is the value below which three quarters lie. The distance between them is the interquartile range (IQR). If quartiles are new to you, Foundations: spread explains them from scratch.
where and are the first and third quartiles, is the interquartile range, and are the lower and upper fences, and is how many IQRs beyond the quartiles a value must lie to be flagged. The NIST/SEMATECH engineering statistics handbook calls values beyond mild outliers and values beyond extreme outliers3.
How you compute a quartile matters more than most people expect. PostgreSQL's percentile_cont interpolates between neighbouring values4, and so does pandas' Series.quantile with its default interpolation='linear'5. Both put the quartile at position in the sorted list, where is 0.25 or 0.75 and is the number of values. BigQuery's APPROX_QUANTILES returns approximate boundaries instead6, which is fine on millions of rows and a surprise on fifteen. Pick one method and write it down, or two reports will disagree about the same fence.
Example: fifteen orders from one October afternoon
Callum takes the fifteen orders completed between 2pm and 4pm on Tuesday 6 October 2026 (invented), sorted by total:
€23.20, €28.60, €33.80, €40.70, €47.80, €54.20, €60.70, €68.70, €74.70, €83.40, €92.20, €107.30, €137.70, €4,620.00, €7,560.00
There are values. The first quartile sits at position , halfway between the 4th value (€40.70) and the 5th (€47.80):
The third quartile sits at position , halfway between the 11th value (€92.20) and the 12th (€107.30):
The interquartile range is . With :
and the lower fence is
The lower fence is below zero, so no order can fall under it. The upper fence is €183.00. Two orders lie above it: €4,620 and €7,560. With the upper fence is , and the same two orders are still flagged as extreme. The €137.70 order stays inside both fences, which is right: €137.70 is a good basket, not a strange one.
Note what the fences did not need: the two big orders. Remove them and recompute, and the quartiles barely move. That is what "robust" means.
Why z scores fail on order values
The most common outlier rule in tutorials is the z score: how many standard deviations a value lies from the mean. Foundations: mean and Foundations: spread cover both ingredients.
where is the z score of value , is the value, is the mean of all values and is their sample standard deviation. The usual rule flags .
The rule has three problems on shop data, and each one alone is enough to drop it.
First, the mean and the standard deviation are both pulled by the very outliers you are hunting. One huge order raises the mean and inflates the standard deviation, which shrinks every z score, including its own. Two huge orders can hide each other. The NIST handbook calls this masking7.
Second, in a small sample the largest possible z score is capped. The NIST handbook gives the bound7.
where is the number of values and is the size of any z score in that sample (Foundations: spread covers the standard deviation behind it). With 10 values the ceiling is , so a rule of can never fire, however absurd the value. Daily checks on small groups (one category, one supplier, one day) hit this all the time.
Third, z scores assume a roughly symmetric, bell shaped distribution. Order values are not symmetric: most orders are modest, a long tail runs to the right. On a long right tail, ordinary large baskets look extreme and the left side never does.
Example: z scores on the same fifteen orders
The fifteen values sum to €13,033.00, so the mean is:
A "typical" order of euro in a shop where thirteen of fifteen orders are under €140 already tells you something is off. The sample standard deviation comes out at €2,191.60. Now the z scores of the two big orders:
and for the larger one, :
With the usual rule of , the hotel sized order at €4,620 is not flagged at all. The €7,560 order scrapes past at 3.05. The ceiling for 15 values is , so the rule had very little room to work with anyway. Remove the €7,560 row and recompute, and the €4,620 order suddenly gets a z score of 3.47: the bigger outlier was masking the smaller one.
If you want a formal test that assumes normal data, Grubbs' test is the classic one, and the NIST handbook recommends other tests when more than one outlier may be present8. For order values, the better answer is a ruler that does not bend.
The median absolute deviation: a ruler that does not bend
Replace the mean with the median and the standard deviation with the median absolute deviation (MAD), and the masking problem goes away. The median is the middle value. The MAD is the median distance of the values from that middle. Foundations: median and mode explains the median if you need it.
where is the median of the values, is the distance of value from the median, is the median of those distances, and is the modified z score of value . The constant rescales the MAD so that, on normal data, is on the same scale as an ordinary z score. Iglewicz and Hoaglin recommend labelling values with as potential outliers, as the NIST handbook reports7. Leys and colleagues make the same case in the title of their paper: do not use the standard deviation around the mean, use the absolute deviation around the median9.
In Python, scipy.stats.median_abs_deviation computes the MAD, and its scale='normal' option divides by roughly 0.67449 for you10. One trap for anyone upgrading old code: pandas used to have a Series.mad method, but it computed the mean absolute deviation, not the median one, and pandas 2.0 removed it11. Compute the MAD explicitly, as in the code later in this chapter.
Example: the modified z score on the fifteen orders
The median of the fifteen values is the 8th one, .
Next, the distance of every value from €68.70, sorted: 0.00, 6.00, 8.00, 14.50, 14.70, 20.90, 23.50, 28.00, 34.90, 38.60, 40.10, 45.50, 69.00, 4,551.30, 7,491.30. The middle of these fifteen distances is the 8th, so .
Now the modified z scores of the largest three orders:
then the hotel sized order, :
and the rug, :
The €137.70 order is ordinary at . Both big orders are flagged by a huge margin, and neither hides the other, because neither the median nor the MAD moved when they arrived.
Example: when the MAD is zero
Callum tries the same score on line item quantities. Most lines at Shannonside Home have a quantity of 1. Take nine lines with quantities 1, 1, 1, 1, 1, 2, 1, 1, 400. The median is 1. The distances from 1 are 0, 0, 0, 0, 0, 1, 0, 0, 399. The median of those distances is 0, so the MAD is 0 and the modified z score divides by zero.
The quartiles fail too: and are both 1, the IQR is 0, and every value that is not 1, including the perfectly normal quantity of 2, falls outside the fences. Any column where more than half the values are identical breaks both robust rulers. The answer is not a cleverer statistic. It is the domain rule from earlier: a line quantity above 50 goes to review.
Money is skewed: take logs first
Order values, product prices and customer lifetime values share a shape: many small amounts and a long tail of larger ones. On that shape, fences computed on the raw values flag far too many ordinary large baskets.
The fix is to compute the fences on the logarithm of the values. A logarithm turns multiplication into addition, so "three times the typical order" becomes a fixed distance on the log scale wherever the typical order sits. Foundations: logarithms has the background.
where is an order value in euro, is the natural logarithm, and is the value on the log scale. Compute , and the fences on , then turn the fences back into euro with and . Zero and negative values have no logarithm, which is one more reason the domain rules run first: they catch those rows before the logs are taken.
Example: how many good orders the raw fences would flag
Assume, for this invented example, that Shannonside Home's order values follow a log normal shape (a normal distribution on the log scale) with a median of €64 and a mean of €84. The distributions section of Foundations explains the shape. For a log normal distribution, mean and median are linked by , where is the standard deviation on the log scale. Solving for :
The quartiles of a normal distribution lie , that is 0.6745 standard deviations, either side of the middle, so in euro:
and the third quartile is
On the raw scale, the IQR is and the upper fence is . How many orders lie above €204.75? On the log scale that is standard deviations above the middle, and a normal table says 5.7% of values lie further out. That is about 114 of the 1,980 orders a month, every one of them a genuine customer, all flagged for review.
On the log scale, the upper fence lies standard deviations above the middle, because the IQR on the log scale is . That fence is , about €469, and only 0.35% of orders lie above it: about 7 a month. A review queue of 7 rows gets read. A queue of 114 gets ignored, and then the real error inside it gets ignored too.
A value can be normal in one group and extreme in another
A rug of 200 cm is ordinary. A cushion of 200 cm is not. Global fences across a whole column miss this, because the cushion hides among the rugs. Compute the fences within a group that makes sense: per product category for dimensions and prices, per customer type for order values, per supplier for feed fields.
Grouping has a cost. Smaller groups mean noisier quartiles, and very small groups fall into the z score trap of having too little data to judge. A practical floor is to skip statistical checks on groups with fewer than about 20 values and rely on the domain rules there.
Grouped checks also catch unit errors, which are some of the most common implausible values in product data. Shannonside Home's known problem: one supplier feed sends dimensions in millimetres, the others in centimetres.
Example: a rug that is 20 metres long
Callum computes fences per category on product length. The nine rugs in the catalogue (invented) are 120, 140, 150, 160, 160, 170, 200, 230 and 240 cm long. With , the first quartile is at position , the 3rd value, 150 cm. The third quartile is at position , the 7th value, 200 cm. The IQR is 50 cm and the upper fence is cm.
A new rug arrives in a supplier feed with a length of 2,000. That is far beyond 275, so it is flagged. Callum adds one more test that he uses for every flagged dimension: divide by 10 and see whether the result lands inside the fences. cm, right inside the range. The row is almost certainly in millimetres. He does not "fix" the value in the warehouse. He fixes the unit mapping for that supplier, so every row from it arrives in centimetres, and the outlier check stays in place to catch the next supplier who changes format.
Look at two columns at once: residuals from a simple model
The hotel sized order and the €7,560 rug are both extreme on order value. On one column, they look alike. On two columns, they look completely different, and that difference is what tells error from genuine extreme.
Plot order value against the number of items. Bigger baskets cost more, roughly in proportion. A simple model captures that relationship, and the distance of each order from the model, its residual, measures how strange the order is given its size. Foundations: regression explains fitting a line.
where is the number of items in order , is its value in euro, is the value the model expects for that many items, and are the intercept and slope fitted by least squares on the log scale, and is the residual. Dividing by the residual standard deviation gives a score that can be judged like a z score. Fitting on logs keeps the huge orders from dominating the fit.
Example: the hotel fits the line, the rug does not
Callum fits the model on 34 recent orders, including the 400 item order (invented data, the points in the chart). Least squares gives , and a residual standard deviation of .
For the 400 item order, the model expects:
That is , about €3,680. The order was worth €4,620, so and the residual is . Divided by , the score is . The order is large, but it is exactly as large as an order of 400 items should be, at a slightly lower price per item, which is what a bulk buyer gets.
For the one item rug at €7,560, the model expects , about €36.60. The residual is , and the score is . Nothing about one item explains that price.
Callum follows up both. Order R482913 came from the Abbeyview Hotel in Ennis, Co. Clare (invented), refurbishing 200 rooms with bath and hand towels at a trade price. It is real, it is the biggest order of the quarter, and Niamh wants more like it. If Shannonside Home starts selling to businesses properly, B2B on Solidus with price lists, quotes and net terms covers the shop side. Order L102877 is from the legacy import, where the old platform stored prices as floating point numbers. The rug cost €75.60, and the import multiplied a value already in euro by 100. It is an error, it inflated 2022 revenue by €7,484.40, and it is fixed in the import mapping, with the raw row kept.
The single column rules flagged both orders. Only the second column told them apart.
Outliers in time: compare with the same weekday and the same week last year
A time series has its own kind of outlier: a day, hour or week that does not fit its context. 30 orders on a Sunday in August may be normal. 30 orders on the Monday after Black Friday is a crisis. The value alone means nothing, so a seasonality aware check compares each day with days that should look like it. Foundations: seasonality and the article on forecasting demand with autocorrelation and seasonality cover the patterns themselves.
Two comparisons do most of the work in a shop:
- Same weekday in recent weeks: compare a Tuesday with the median of the previous eight Tuesdays, using the MAD of those Tuesdays as the ruler.
- Same period last year: compare Black Friday with last year's Black Friday, not with an ordinary Friday. Retail calendars move (Black Friday, Easter, bank holidays), so match the event, not the date.
where is the count on day , is the median of the same weekday over the previous eight weeks, is the median absolute deviation of those eight values, is , which puts the MAD on the scale of a standard deviation, and is the robust score of day . Flag , which is the band drawn in the chart below. The median section of Foundations explains why the median holds steady here.
For longer or messier series, decompose first. Seasonal and trend decomposition using LOESS (STL) splits a series into trend, seasonal and remainder parts, and its robust option keeps occasional unusual values from distorting the trend and seasonal parts, so they show up in the remainder where you can score them12. In Python, statsmodels.tsa.seasonal.STL takes a period and a robust flag13. Hochenbaum, Vallis and Kejariwal published a method built on exactly this idea, seasonal decomposition followed by the median and MAD on what remains, to find anomalies in the metrics of large web services, which have strong seasonal cycles14. Inside BigQuery, ML.DETECT_ANOMALIES does a model based version of the same for time series models, returning a lower bound, an upper bound and an anomaly probability for each point15.
Example: two red days in November
Callum's weekly check flags two days in November 2026 (invented numbers, as in the chart).
Tuesday 17 November has 23 orders. The previous eight Tuesdays have a median of 62 and a MAD of 4:
A score of is far outside the band of plus or minus 3.
Friday 27 November, Black Friday, has 241 orders. The previous eight Fridays have a median of 68 and a MAD of 5:
Both have and are flagged. Only one is a problem. For Black Friday, Callum runs the second comparison: Black Friday 2025, on 28 November 2025, brought 226 orders. The change is , close to the shop's invented year on year growth of 5%. Against its own event, the day is grand. He adds a calendar table with Black Friday, Cyber Monday, the Christmas cut off and the January sale, and his check compares those days with last year's equivalent instead of with ordinary weekdays. The other day, Tuesday 17, needs a different kind of look, and gets the next section.
Here is the check in PostgreSQL, run on the shop database. Two details carry the weight. PostgreSQL cannot use percentile_cont as a window function, because ordered set aggregates are not allowed there16, so the baseline is computed in a lateral subquery for each day. And because completed_at holds UTC without a zone, the day boundary needs two at time zone steps: the first says "this is UTC", the second converts to Irish time17.
-- PostgreSQL: each day's orders against the same weekday in the previous eight weeks
with daily as (
select ((completed_at at time zone 'UTC') at time zone 'Europe/Dublin')::date as day,
count(*) as orders
from spree_orders
where state = 'complete'
group by 1
)
select d.day, d.orders, base.median_orders, spread.mad_orders,
round(((d.orders - base.median_orders)
/ nullif(1.4826 * spread.mad_orders, 0))::numeric, 2) as robust_score
from daily d
cross join lateral (
select percentile_cont(0.5) within group (order by p.orders) as median_orders
from daily p
where p.day between d.day - 56 and d.day - 7
and extract(isodow from p.day) = extract(isodow from d.day)
) base
cross join lateral (
select percentile_cont(0.5) within group (order by abs(p.orders - base.median_orders)) as mad_orders
from daily p
where p.day between d.day - 56 and d.day - 7
and extract(isodow from p.day) = extract(isodow from d.day)
) spread
where d.day >= date '2026-11-01'
order by d.day;
The nullif protects against a MAD of zero, the trap from earlier. Days with fewer than eight earlier weeks of history get a baseline from whatever weeks exist, so the first weeks of any new series deserve less trust.
A volume drop is a pipeline anomaly, not a value outlier
Value outliers live inside rows. Volume anomalies are about rows that are missing or doubled. They come from a different mechanism, the pipeline, and cleaning cannot fix them. You cannot winsorise a missing order back into existence.
The test for which kind you face is a reconciliation: count the same thing in the source and in the warehouse. If the source has the rows and the warehouse does not, the pipeline lost them, and the fix is to reload. If both are low, the business really had a bad day, and the question goes to Niamh: was the checkout broken, did a payment provider fail, did an advert stop? A later chapter in this series covers observability, the monitoring that catches freshness and volume problems automatically. Here, the point is narrower: never treat a volume anomaly as a data value to clean.
Example: the Tuesday with 23 orders
Callum counts completed orders for 17 November 2026 in the shop database directly:
-- PostgreSQL, on the shop database: completed orders on 17 November, Irish time
select count(*)
from spree_orders
where state = 'complete'
and ((completed_at at time zone 'UTC') at time zone 'Europe/Dublin')::date = date '2026-11-17';
The answer is 61. The warehouse has 23. The business had a normal Tuesday. The nightly extract had timed out after loading the morning's orders, and the job reported success because it caught the timeout and carried on (the invented cause). The fix is a reload of that day and a change to the job so that a timeout fails loudly. No row is cleaned, imputed or flagged, because no row was wrong. The rows were simply not there.
Had he not checked, the dip would have gone into the weekly report as "a slow Tuesday", and someone might have paused an advert in response.
How one row moves the mean and barely moves the median
Outliers matter because they move the numbers people act on. The mean moves with every value. The median moves only when values cross the middle. The article on why averages mislead makes the general case. Here is the arithmetic for a single row, with Foundations: mean for the background.
where is the number of values before the new one, is their mean, is the added value, is the new mean, and is how far the mean moves. The shift grows with how far the new value is from the mean and shrinks with the number of values. The median, by contrast, moves by at most one position in the sorted list, whatever the size of the new value.
Example: October with and without the strange rows
Take a month of 1,980 orders at a mean of €84.00, so revenue of euro, and an invented median of €64.00. Add the hotel order:
One order out of 1,981 lifts the AOV by euro, or 2.7%. The median stays at €64.00, because the 1,980 orders are so dense around the middle that moving one position changes nothing at the cent.
Now the decimal shift error instead. It does not add an order: it turns an existing €75.60 order into €7,560.00, so revenue grows by euro:
With both, the mean is euro.
The lesson for reporting: the hotel order belongs in revenue and in the mean, because it happened. The error belongs in neither. And for "what does a typical customer spend", the median was the right number from the start. If the board pack shows only the mean AOV, one hotel can make a quiet month look like a breakthrough. Showing uncertainty honestly covers how to present numbers like these without overstating them.
What to do with an outlier: five options and one rule
Once a row is flagged and investigated, there are five things you can do with it. Which one is right depends on the kind of outlier and on the analysis, not on how ugly the row looks.
| Option | When | Example at Shannonside Home |
|---|---|---|
| Correct at the source | The value is wrong and the true value is known | Fix the legacy import mapping so the rug is €75.60 |
| Keep it as it is | The value is real | The hotel order stays in revenue |
| Flag and exclude from one analysis | The value is real but distorts a specific question | Leave the hotel out of "typical household basket" analysis, with a note |
| Cap or winsorise | A model or average must not be dominated by a few real extremes | Cap order values at the 99th percentile for a basket size model |
| Quarantine for review | Not yet known | The 1970 order waits until Callum traces the import |
And the rule: never delete automatically. A rule that silently removes rows will one day remove the hotel. Worse, deletion hides the evidence of a source problem, so the error keeps arriving. Every flagged row stays, with its flag, its reason and a decision recorded by a person.
Winsorising deserves a closer look, because it is often misused. To winsorise is to replace values beyond a chosen percentile with the value at that percentile. The values stay in the data, the extreme ones are pulled in. The spread section of Foundations covers percentiles.
where is the original value, and are the chosen lower and upper percentiles, and is the winsorised value. In pandas, Series.clip(lower, upper) does this once you have the percentiles5. SciPy offers scipy.stats.mstats.winsorize with limits given as the fraction to cut on each side18. In SQL it is least(greatest(x, p_low), p_high).
Example: a capped average for a model, never for revenue
Callum is building a simple model of basket size for Niamh's free delivery threshold. The hotel order and 19 other very large October orders would dominate it. He caps order values at the 99th percentile, €355 (invented). The 20 orders above it total €13,880. After capping, they count as euro, so the capped total is euro and the capped mean is:
That of €82.87 is a fair input for a model of household baskets. It is a wrong number for anything to do with money. Used as revenue, it would understate October by €6,780. So the capped column lives next to the real one, named for what it is (order_total_capped_p99), and never replaces it.
Never delete automatically: flags and a review log in dbt
The practical way to keep every row and still give each analysis what it needs is a flag model plus a review log. The flag model computes why a row is suspicious. The review log records what a person decided. Every report then chooses rows by decision, out in the open.
Callum keeps the review log as a dbt seed, a small CSV file in the dbt project that dbt loads as a table. Because it lives in git, every decision has an author and a date in the history.
order_id,decision,reason,reviewed_by,reviewed_on
482913,keep,"Abbeyview Hotel refurbishment, confirmed with Niamh",callum,2026-10-08
102877,correct_at_source,"Legacy import multiplied price by 100, mapping fixed",callum,2026-10-09
412,quarantine,"Empty legacy date became 1970-01-01, tracing import",callum,2026-10-09
1907,correct_at_source,"Legacy return stored as negative sale line",callum,2026-10-09
The flag model joins the rules to the decisions. This one is written for BigQuery, where Callum's warehouse lives:
-- models/intermediate/int_order_outlier_flags.sql (BigQuery)
with orders as (
select * from {{ ref('stg_shop__orders') }}
),
reviews as (
select * from {{ ref('order_outlier_reviews') }}
)
select
o.order_id,
o.order_number,
o.completed_at,
o.order_total_eur,
o.item_count,
-- min_line_quantity and max_line_quantity are aggregated from spree_line_items in staging
case
when o.completed_at < timestamp '2022-01-04 00:00:00 UTC' then 'impossible_before_first_trading_day'
when o.min_line_quantity < 1 then 'impossible_quantity_below_one'
when o.order_total_eur > 2500 or o.max_line_quantity > 50 then 'implausible_needs_review'
end as outlier_reason,
coalesce(r.decision, 'not_reviewed') as review_decision
from orders as o
left join reviews as r
on o.order_id = r.order_id
Every row comes out, flagged or not. Downstream, the revenue model keeps everything except decisions of quarantine and rows whose corrected value has arrived from the source, while the basket analysis also leaves out rows marked as business orders. Each exclusion is a where clause on a named decision, which makes it visible in the code and countable in a reconciliation. A later chapter in this series shows how to report the cleaned totals next to the source totals, so finance can see every step.
To catch new outliers without blocking the pipeline, Callum writes a custom generic data test in dbt19. It returns the rows whose modified z score exceeds a threshold, and it runs with severity: warn, so a new extreme value raises a warning for review instead of failing the build20. Here is the test:
-- tests/generic/robust_outliers.sql (BigQuery)
{% test robust_outliers(model, column_name, threshold=3.5) %}
with base as (
select cast({{ column_name }} as float64) as v
from {{ model }}
where {{ column_name }} is not null
),
centre as (
select approx_quantiles(v, 2)[offset(1)] as med from base
),
spread as (
select approx_quantiles(abs(b.v - c.med), 2)[offset(1)] as mad
from base as b
cross join centre as c
)
select b.v, 0.6745 * (b.v - c.med) / nullif(s.mad, 0) as modified_z
from base as b
cross join centre as c
cross join spread as s
where abs(0.6745 * (b.v - c.med) / nullif(s.mad, 0)) > {{ threshold }}
{% endtest %}
APPROX_QUANTILES(v, 2) returns three values, the approximate minimum, median and maximum, so [offset(1)] picks the median6. On a few thousand rows the approximation is close. On a handful it is not, so this test belongs on tables, not on tiny groups. In the model's properties file:
models:
- name: int_order_outlier_flags
columns:
- name: order_total_eur
data_tests:
- robust_outliers:
arguments:
threshold: 3.5
config:
severity: warn
The arguments key is the current way to pass test arguments in recent dbt versions, and older versions take the argument at the top level instead19. Run on raw order values, this test will warn about every big basket, because money is skewed. Point it at a log column (ln(order_total_eur) computed in the model) and it warns about the handful that matter.
Example: what the warning looks like on a normal week
In the week after the hotel order, dbt build finishes with one warning: robust_outliers on int_order_outlier_flags found 2 rows on the log scale. Callum looks them up. One is the hotel order, already in the review log as keep. The other is a new order of 14 lamps for a dental practice in Nenagh, Co. Tipperary (invented), which he confirms with Niamh and adds to the seed as keep. Nothing was deleted, the build was not blocked, and both decisions are in git with his name on them.
A small, tested detector in Python
For analysis outside dbt, for example in a notebook while profiling a new source, Callum uses one function that labels and never removes. It applies the log scale fences and the modified z score and returns one output row for every input row.
# outliers.py
import numpy as np
import pandas as pd
def flag_outliers(values: pd.Series, k: float = 1.5, threshold: float = 3.5) -> pd.DataFrame:
"""Label, never remove: one row out for every row in, with the evidence."""
positive = values.where(values > 0)
logged = np.log(positive)
q1, q3 = logged.quantile([0.25, 0.75])
iqr = q3 - q1
lower, upper = np.exp(q1 - k * iqr), np.exp(q3 + k * iqr)
median = values.median()
mad = (values - median).abs().median()
if mad == 0:
modified_z = pd.Series(np.nan, index=values.index)
else:
modified_z = 0.6745 * (values - median) / mad
return pd.DataFrame({
"value": values,
"impossible": values <= 0,
"outside_log_fences": (positive < lower) | (positive > upper),
"modified_z": modified_z.round(2),
"mad_flag": modified_z.abs() > threshold,
})
Line by line: values.where(values > 0) turns zero and negative values into missing values, so the logarithm never sees them, and the impossible column reports them instead. The fences are computed on the log scale and turned back into euro with np.exp. If the MAD is zero, the function returns no score rather than dividing by zero. Nothing is filtered: the output has exactly as many rows as the input.
Callum works test first, so the behaviour is pinned down by tests before anyone relies on it:
# test_outliers.py
import pandas as pd
import pytest
from outliers import flag_outliers
AFTERNOON = [23.20, 28.60, 33.80, 40.70, 47.80, 54.20, 60.70, 68.70,
74.70, 83.40, 92.20, 107.30, 137.70, 4620.00, 7560.00]
def test_flags_the_two_extremes_and_nothing_else():
flags = flag_outliers(pd.Series(AFTERNOON))
assert flags["mad_flag"].tolist() == [False] * 13 + [True, True]
assert flags["outside_log_fences"].tolist() == [False] * 13 + [True, True]
assert flags.loc[13, "modified_z"] == pytest.approx(109.64)
def test_zero_mad_gives_no_score_instead_of_a_division_by_zero():
quantities = pd.Series([1, 1, 1, 1, 1, 2, 1, 1, 400])
flags = flag_outliers(quantities)
assert flags["modified_z"].isna().all()
assert not flags["mad_flag"].any()
def test_never_drops_a_row():
values = pd.Series([-3.0, 0.0, 64.0, 70.0, 7560.0])
flags = flag_outliers(values)
assert len(flags) == len(values)
assert flags["impossible"].tolist() == [True, True, False, False, False]
Example: the detector on the October afternoon
Run on the fifteen orders from earlier, the last four rows of the output read:
| value | impossible | outside_log_fences | modified_z | mad_flag |
|---|---|---|---|---|
| 107.30 | False | False | 0.93 | False |
| 137.70 | False | False | 1.66 | False |
| 4620.00 | False | True | 109.64 | True |
| 7560.00 | False | True | 180.46 | True |
The numbers match the hand calculation above to the cent. The log fences for this sample work out at €13.03 and €336.82, so both big orders sit outside them and nothing else does. The detector agrees with the arithmetic, the tests pin the edge cases, and a person still decides what each flagged row means.
Beyond the basics: when a model earns its place
There are many more sophisticated detectors. Isolation forests, for example, isolate each row with random splits across many columns and score rows that are isolated in few splits as anomalous21. The scikit-learn library ships one as sklearn.ensemble.IsolationForest22. They are useful when there are many columns and no obvious pair to plot, such as fraud signals across payment, address, device and basket features.
They have costs a small shop feels. Their scores are hard to explain to the owner, they need tuning (an isolation forest asks you to guess the share of anomalies up front), and they still cannot tell a hotel from a typing mistake. Every row they flag goes through the same investigation as a row flagged by a fence.
Example: why Callum does not need one yet
Callum counts what his simple stack catches in a quarter (invented numbers): the domain rules flag 31 impossible rows, all from the legacy import; the log fences and the modified z score flag 22 implausible orders, of which 19 are real business customers and 3 are errors; the weekday check flags 4 days, of which 3 are calendar events and 1 is a pipeline fault. Every flag was explainable to Niamh in one sentence. An isolation forest might find something subtle across many columns, but until the shop has a fraud problem those columns do not describe, the simpler stack is the better investment of his time.
A checklist for outliers and anomalies
| Step | Question | Tool |
|---|---|---|
| 1 | Is the value impossible? | Domain rules in SQL, written down with owner and reason |
| 2 | Is it a standardisation problem in disguise (units, zones, currency)? | Divide by 10, check the zone, check the currency, then fix the mapping |
| 3 | Is it unusual for its group? | Log scale fences or modified z score per category, customer type or supplier |
| 4 | Is it unusual given another column? | Residual from a simple model, such as value against items |
| 5 | Is a day or week unusual for its context? | Same weekday median and MAD, same event last year, STL for longer series |
| 6 | Is it a missing or doubled volume rather than a strange value? | Reconcile counts against the source, reload if the pipeline lost rows |
| 7 | What does the business say? | Ask the owner, record the decision in the review log |
| 8 | Which analyses should include it? | Keep in totals if real, exclude from a specific analysis with a flag, cap only for models |
Conclusion
An extreme value is a question, not a verdict. Sort it first: impossible values break a rule of the business, implausible ones deserve a look, genuine extremes are often the most valuable rows you have. Check domain rules before any statistic, because facts about the business are stronger than distributions. When you do use statistics on shop data, use robust ones: quartile fences and the median absolute deviation, on the log scale for money, within sensible groups, and with a second column where one exists. In time series, compare each day with days that should look like it, including the same event last year, and remember that a drop in volume is a pipeline question to reconcile, not a value to clean. Then decide row by row: correct at the source, keep, flag for one analysis, or cap for a model. Never delete automatically. The row you were about to throw away might be the hotel.
