SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed

New conversation

What can I help with?

Ask about this page, get a hint on a challenge, or explore SQL concepts.

I know what's on this page and can give answers grounded in SQL Boy content.

Current page

Calculating Percentiles Median Sql

/blog/calculating-percentiles-median-sql

Usage status will load after login
SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog
Back to Blog
Published 2026-01-20
6 min read

Calculating Percentiles and Median in SQL

sqlstatisticsdata-analysiswindow-functionsanalytics

Author

SQL Boy Team

Editorial Team at SQL Boy

This article is maintained as part of SQL Boy's hands-on SQL library.

We aim to keep examples runnable, call out dialect differences, and revise unclear sections over time.

Read editorial standardsAbout SQL BoyRequest a correction

If a result or dialect note looks wrong, email [email protected] with the article URL and the section you want reviewed.

When analyzing data, averages can be misleading. A few outliers can skew the mean dramatically. That's why professionals rely on median and percentiles for more robust insights.

But SQL doesn't have a built-in MEDIAN() function in most databases. Let's explore how to calculate these statistics anyway.

Distribution curve highlighting median and percentiles
Distribution curve highlighting median and percentiles

Why Median Matters

Consider employee salaries:

  • Mean salary: $100,000
  • But if the CEO makes $1,000,000 and everyone else makes $50,000, the mean is misleading!
  • Median salary: $50,000 (the "middle" value) tells the real story.

Method 1: Using PERCENT_RANK for Percentiles

The PERCENT_RANK() function assigns a percentile rank (0 to 1) to each row:

Interactive SQL
Loading...

A percentile of 50 means half the data is below that value.

Method 2: Finding the Median with Window Functions

The median is the value at the 50th percentile. Here's how to find it:

Interactive SQL
Loading...

How This Works

  1. ROW_NUMBER() assigns position 1 to N
  2. COUNT(*) OVER () gets the total count
  3. For odd counts: (N+1)/2 gives the middle position
  4. For even counts: Average of positions N/2 and N/2+1

Method 3: NTILE for Quartiles

NTILE(4) divides data into 4 equal groups (quartiles):

Interactive SQL
Loading...

You can use NTILE(10) for deciles or NTILE(100) for fine-grained percentiles.

Method 4: Percentile Boundaries

Find the value at a specific percentile (e.g., 90th percentile):

Interactive SQL
Loading...

Calculating Multiple Percentiles at Once

Need P25, P50 (median), and P75? Use conditional aggregation:

Interactive SQL
Loading...

Group-Level Percentiles

Calculate median salary per department:

SELECT 
  department,
  AVG(salary) as median_salary
FROM (
  SELECT 
    department,
    salary,
    ROW_NUMBER() OVER (
      PARTITION BY department 
      ORDER BY salary
    ) as rn,
    COUNT(*) OVER (PARTITION BY department) as dept_count
  FROM employees
)
WHERE rn IN ((dept_count + 1) / 2, (dept_count + 2) / 2)
GROUP BY department;

Comparison: Mean vs Median

Interactive SQL
Loading...

Notice how the outlier ($500,000) dramatically affects the mean but not the median!

Quick Reference

StatisticSQL Approach
Percentile rankPERCENT_RANK() OVER (ORDER BY col)
MedianROW_NUMBER() + middle position formula
Quartiles (4 groups)NTILE(4) OVER (ORDER BY col)
Deciles (10 groups)NTILE(10) OVER (ORDER BY col)
Specific percentileNTILE(100) + filter

Best Practices

  1. Use median for skewed data: Income, prices, and response times often have outliers.

  2. Report both mean and median: If they differ significantly, your data is skewed.

  3. Consider NTILE limitations: With small datasets, NTILE groups may be uneven.

  4. Index the ORDER BY column: Percentile calculations sort data, so indexes help.

Tool Workflow

Use tools when percentile SQL is correct mathematically but still hard to audit

Median and percentile queries often combine ranking, tiling, and nested calculations. Use the tools to inspect the window logic and confirm that the statistic matches the business question.

SQL Query Explainer

Break percentile queries into readable clauses so ranking, partitioning, and aggregation logic are easier to verify.

Query Analysis Workflow Hub

Use the broader workflow when analytical SQL needs explanation, validation, and result-shape review together.

Conclusion

While SQL lacks a native MEDIAN() in most databases, window functions provide powerful alternatives:

  • PERCENT_RANK() for percentile ranks
  • NTILE() for dividing into groups
  • ROW_NUMBER() with arithmetic for exact median

These techniques give you robust statistical insights that go beyond simple averages.

Related Articles

  • Understanding Window Functions: A Practical Guide for the foundation behind ranking and distribution-style analytics.
  • Descriptive Statistics in SQL: Mean, Median, Mode, and More for the broader summary-statistics toolkit around percentiles.
  • SQL Histograms and Frequency Distributions for another way to understand distributions beyond a single average.
Share this article:

Related Articles

sqlanalytics

Building Histograms and Frequency Distributions in SQL

Learn how to build histograms, bucket data into ranges, and compute frequency distributions directly in SQL without external tools.

Read more
sqlanalytics

SQL for Anomaly Detection: Finding Outliers

Learn how to detect anomalies and statistical outliers in your data using SQL with Z-score, IQR, and moving average methods.

Read more
sqldata-analysis

SQL for Data Analysis: The Ultimate Guide

Move beyond basic SELECTs. Master the core SQL techniques for real-world data analysis: Data Cleaning, Time-Series Analysis, Window Functions, and Cohort Analysis.

Read more
Previous

Removing Duplicate Rows in SQL: A Complete Guide

Next

SQL Conditional Aggregation: Beyond Basic GROUP BY

Comments

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed