Lecture

ROW_NUMBER and NTILE

ROW_NUMBER() and NTILE(n) are window functions used to analyze ordered data in SQL.

  • ROW_NUMBER() assigns a unique number to each row according to the specified order.
  • NTILE(n) divides rows into n nearly equal-sized groups, useful for quartiles, deciles, and other distributions.

Syntax

The basic syntax for ROW_NUMBER() and NTILE(n) is as follows:

ROW_NUMBER and NTILE syntax
SELECT column1, ROW_NUMBER() OVER (ORDER BY column2) AS row_num, NTILE(n) OVER (ORDER BY column2) AS group_id FROM table_name;
  • OVER (ORDER BY ...) defines how the rows are sorted before numbering
  • NTILE(n) distributes the ordered rows into n groups

Example: Learners' Scores

Suppose we track learners’ final_score in a course and want to assign row numbers and split them into quartiles based on their scores.

You can use ROW_NUMBER() and NTILE(4) to assign row numbers and group learners into quartiles:

Rank learners and group them into quartiles
SELECT name, final_score, ROW_NUMBER() OVER (ORDER BY final_score DESC) AS row_num, NTILE(4) OVER (ORDER BY final_score DESC) AS quartile FROM course_progress;

Output:

namefinal_scorerow_numquartile
Alex9811
Sara9521
Daniel9132
Mia9042
Emma8653
Noah8363
John8074
Leo7884
  • ROW_NUMBER() assigns a unique number to each row according to the specified order.
  • NTILE(4) divides the rows into four nearly equal-sized quartile groups.

How do ROW_NUMBER and NTILE differ?

  • ROW_NUMBER() is best when you need a strict sequence or to uniquely identify rows (e.g., pagination, deduplication).
  • NTILE(n) is best when you want to segment data into groups for analysis (e.g., quartiles, deciles, performance tiers).
Quiz
0 / 1

What SQL window function allows you to access the previous row's value?

The SQL function to access the previous row's value is .
LEAD
LAG
ROW_NUMBER
RANK

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result