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 13 July 2026

  • 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.

  • NTILE splits 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_NUMBER plus COUNT(*) to pick the middle row(s) manually.

  • https://support.teradata.com/community?id=community_blog&sys_id=9aa893671b9bfb00682ca8233a4bcb74
  • https://sqlmaxx.com/learn-sql/ntile/
All Advanced SQL interview questions