Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 84/ 160
05. Window Functions & Analytical SQL

Distribution & Bucketing Functions: NTILE(), PERCENT_RANK(), CUME_DIST()

Bucket and score distributions with NTILE, PERCENT_RANK, and CUME_DIST.

IntermediateNTILE · PERCENT_RANK3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

NTILE cuts a sorted list into equal piles. PERCENT_RANK and CUME_DIST tell you how high up the list each row is, as a number between 0 and 1.

Think of it like…

Lining up a class by height: NTILE(4) splits the line into four equal groups; PERCENT_RANK says how far along the line each student stands (0 for the first, 1 for the last); CUME_DIST says what share of the class is this tall or shorter.

Where you’ve seen it

Customer segmentation: SELECT customer_id, spend, NTILE(4) OVER (ORDER BY spend DESC) AS quartile FROM customer_spend;. Quartile 1 is the top 25% of spenders, which marketing targets with a loyalty offer.

Words you’ll hear

NTILE(n)
Bucket number 1…n; bucket sizes differ by at most one row.
PERCENT_RANK
(rank − 1) / (total rows − 1); the first row is 0.
CUME_DIST
(rows with value ≤ current) / total rows; the last row is 1.
PERCENTILE_CONT / DISC
Ordered-set aggregates for medians and percentiles: interpolated or actual value.

Visual diagram

Loading interactive diagram

Theory & example queries

NTILE for equal-sized buckets

NTILE(n) numbers rows 1 to n so each bucket gets roughly the same number of rows; if the rows don't divide evenly, the first buckets get one extra row. It's based purely on position in the order, so tied values can end up in different buckets, and buckets say nothing about value ranges.

That makes NTILE right for "split customers into four equal groups", and wrong for "customers who spent ₹0–1,000, ₹1,000–5,000 …". For value-based ranges use CASE, or PostgreSQL's WIDTH_BUCKET(value, low, high, count).

Spend quartiles per countryQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  country,4  NTILE(4) OVER (5    PARTITION BY6      country7    ORDER BY8      spend DESC9  ) AS quartile10FROM11  customer_spend;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
customer_idcountryquartile
104India1
118India2
202Singapore1
219Singapore2

Note: Illustrative customers and buckets; the spend ordering and partition size determine each NTILE value.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: NTILE = equal row counts, not equal value ranges.

Relative position and percentiles

PERCENT_RANK and CUME_DIST both express position as a fraction. Use CUME_DIST for "top 10%" filters: CUME_DIST() OVER (ORDER BY spend DESC) <= 0.10 keeps the top tenth, and tied rows always get the same value, so a tie at the boundary is treated consistently. PERCENT_RANK starts at exactly 0, which suits "percentile score" displays.

For a single percentile of a group, such as the median, use the ordered-set aggregates: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) interpolates between the two middle values, and PERCENTILE_DISC returns an actual value from the data. They're supported in PostgreSQL, SQL Server (as window functions), Oracle and Snowflake; MySQL has no built-in median.

Median and 90th percentile order value per monthQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  date_trunc('month', created_at) AS MONTH,3  PERCENTILE_CONT(0.5) WITHIN GROUP (4    ORDER BY5      amount6  ) AS median,7  PERCENTILE_CONT(0.9) WITHIN GROUP (8    ORDER BY9      amount10  ) AS p9011FROM12  orders13GROUP BY14  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
monthmedianp90
2026-09-014801520
2026-10-015251680
2026-11-015101590

Note: Illustrative continuous percentiles for monthly order amounts in currency units.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: CUME_DIST for top-X% filters; PERCENTILE_CONT for medians.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Question

Decide what you need

Equal-sized groups means NTILE. A position score means PERCENT_RANK or CUME_DIST. A single statistic like the median means PERCENTILE_CONT.

Focus at this step

quartiles · top 10% · median

What to watch at this step
Match
function to question
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

NTILE(n) splits ordered rows into n buckets of (almost) equal size, such as quartiles with NTILE(4). PERCENT_RANK() gives each row's relative rank from 0 to 1: (rank − 1) / (rows − 1). CUME_DIST() gives the fraction of rows with a value less than or equal to the current one, from just above 0 up to 1. For medians and other percentiles, use PERCENTILE_CONT or PERCENTILE_DISC.

Why it matters: "Top 10% of customers by spend", "split users into quartiles" and "what's the median order value?" come up constantly in analytics, segmentation and interviews. Each function answers a slightly different question, and NTILE in particular behaves unexpectedly with ties.

When to reach for it

  • Customer and product segmentation by quartile or decile
  • Selecting the top 10% by spend or activity
  • Medians and latency percentiles in reports

When to avoid or be careful

  • NTILE for value-range buckets
  • Using AVG when the distribution is skewed and the median is what matters
  • Ignoring how ties fall at bucket boundaries

NTILE vs PERCENT_RANK / CUME_DIST vs PERCENTILE_CONT

NTILE(n)
Best for: Equal-sized segments: quartiles, deciles

Strengths: Simple bucket numbers for every row.

Watch out: Ties can be split; buckets aren't value ranges.

PERCENT_RANK / CUME_DIST
Best for: Top-X% filters and percentile scores per row

Strengths: Ties always get the same value.

Watch out: Fractions, not bucket labels.

PERCENTILE_CONT / PERCENTILE_DISC
Best for: Median, p90, p99 of a group

Strengths: Exact statistic per group.

Watch out: Returns one value per group, not per row; not in MySQL.

Interview signals & numbers to know

When this topic comes up

  • “Split customers into quartiles”
  • “Top 10% of users by spend”
  • “What's the median order value?”
  • p95 / p99 latency
  • Percentile rank

Benchmarks & rules of thumb

0 to 1 -
range of PERCENT_RANK (first row is 0)
(0, 1] -
range of CUME_DIST (last row is 1)
0.5 -
the median in PERCENTILE_CONT

Common mistakes & follow-ups

Common interview mistakes

  • Using NTILE(10) and assuming each decile covers an equal range of values.
  • Filtering "top 10%" with NTILE and getting inconsistent results when values tie at the boundary.
  • Reporting the average order value for a skewed distribution where the median tells the real story.

Likely interviewer follow-ups

  • What's the difference between PERCENT_RANK and CUME_DIST?
  • How would you compute the median in PostgreSQL, and in MySQL?
  • How does NTILE handle 10 rows split into 3 buckets?
Interview tip: Work through one four-row example for all three functions. Seeing NTILE split the tied values is the moment most interviewers are looking for.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Distribution & Bucketing Functions: NTILE(), PERCENT_RANK(), CUME_DIST() with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Ranking Functions: ROW_NUMBER(), RANK(), DENSE_RANK()
Next topic
Offset Functions: LAG() & LEAD() (Accessing Previous & Next Rows)