How do you compute a median or arbitrary quantile directly in SQL, and what are the trade-offs between using PERCENTILE functions versus NTILE?
Last updated
Use the ordered-set aggregate
PERCENTILE_CONT(q) WITHIN GROUP (ORDER BY col): median is q = 0.5, and it is exact with proper interpolation and tie handling.NTILEsplits rows into equal-size buckets, so it only approximates quantile cutoffs (imprecise with ties or small data). Use it to assign rows to cohorts.On engines without percentile functions, use
ROW_NUMBERplusCOUNT(*)to pick the middle row(s) manually.