Find outliers with percentiles
Order values and split them into equal tiles with NTILE; the first and last tiles hold the extremes that deserve a look.
The task
orders.total has a few absurd values: a 0.01 test order, a 999999 placeholder. Rank-based outliers surface them without choosing a threshold by hand.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH buckets AS (
SELECT id, total,
NTILE(20) OVER (ORDER BY total) AS vigintile
FROM orders
WHERE total IS NOT NULL
)
SELECT id, total, vigintile
FROM buckets
WHERE vigintile IN (1, 20)
ORDER BY total;
它的運作方式
NTILE(20) orders every non-NULL total and stamps each row with a tile number from 1 (lowest) to 20 (highest), each tile holding five percent of the rows. Selecting tiles 1 and 20 shows the bottom and top five percent. Values far from the mass of data are the candidates for correction or exclusion.
Variations
True percentile cut (PostgreSQL, Oracle)
PostgreSQL OracleWITH bounds AS (
SELECT
PERCENTILE_CONT(0.01) WITHIN GROUP (ORDER BY total) AS p01,
PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY total) AS p99
FROM orders
)
SELECT o.id, o.total
FROM orders o, bounds b
WHERE o.total < b.p01 OR o.total > b.p99;
Where the extremes sit per category
WITH buckets AS (
SELECT status, total,
NTILE(20) OVER (PARTITION BY status ORDER BY total) AS vigintile
FROM orders
WHERE total IS NOT NULL
)
SELECT status, total
FROM buckets
WHERE vigintile IN (1, 20);
Questions that come up
NTILE or percentile_cont?
NTILE runs on all five engines (SQLite since 3.25, MySQL since 8.0) and answers 'show me the bottom and top five percent' directly. PERCENTILE_CONT gives the exact interpolated threshold, while NTILE tiles differ in size by one row when the count does not divide evenly. Support is uneven: PostgreSQL and Oracle take the WITHIN GROUP aggregate form shown above, SQL Server only accepts it as a window function with OVER (), SQLite 3.47+ builds that include the percentile functions (the sqlite3 shell does) spell it percentile_cont(total, 0.99), and MySQL has none. Start with NTILE; switch when you need the numeric threshold itself.
Keep reading
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.