r/SQL • u/Valuable-Ant3465 • May 07 '26
SQL Server How find outlieers with TSQL
Hi all,
is there any way to integrate into my TSQL code logic to find statistical Outliers from list of numbers ? My list could contain very low number of observations within 5-10 range.
357066
339594
410763
98314913 --> Outlier
291277
4087 --> Outlier
981 --> Outlier
31 --> Outlier
Thanks to all
0
Upvotes
4
u/svtr May 07 '26
something along those lines ? I didn't use window functions here, easier to get the approach across I think.... but well, it highly depends on the definition of what an outlier is. Oh and take care off the possible implicity type conversion between a decimal and an integer, but well... I'll leave that to you.
16
u/Eleventhousand May 07 '26
I usually use one of two methods: anything over +/- 2 standard deviations, or the IQR + multiplier fencing method.
I can't really give you the code because you haven't provided any structure to your table.
You can either google those two methods or ask for more help.
2
u/13ass13ass May 07 '26
For your example coerce to text and get the length of the number string and count rows grouped by stringified number length
2
u/GrandOldFarty May 08 '26
IQR + multiplier fencing is good but with such large outlier values next to such small ones the value of Q3-Q1 is very large, which pushes the lower fence into negative territory, so the smaller values won’t get flagged.
MAD (median absolute deviation) is based on median values which are more resilient to extreme outliers in small datasets. No matter how big the final number in the set is, the median stays where it is.
Log transforms also help reduce distribution of very large values.
I think MAD + log10 transformation is the winner here
3
u/HandbagHawker May 07 '26
your list is too small to have "statistical" outliers. if you have a target range, variance/tolerance from a predetermined mean, etc., but you can look at that small of a dataset in the absence of other information and decide what is statistically valid or not
1
u/Equivalent_Lunch_944 May 07 '26
If you want something quick and dirty you could just do a WHERE clause above and below whatever values you want. But if you want outliers as defined by an IQR you should calculate that first.