Skip to content

NTILE

NTILE(numeric_expr) OVER ([PARTITION BY column_expr [, …]] [ORDER BY column_expr [ASC | DESC] [, …]])

Section titled “NTILE(numeric_expr) OVER ([PARTITION BY column_expr [, …]] [ORDER BY column_expr [ASC | DESC] [, …]])”
  • numeric_expr: Represents the integer value which would be used to divide the result set into equal portions. If the number passed is more than the number of rows in the window, then some of these partitions are empty.
  • partition by column_expr: This is an optional parameter used to break the result set into smaller groups, based on the column expression(s) provided. Rows in each partition are processed separately for the functions.
  • order by column_expr: Another optional parameter used to sort the rows within each partition. This is based on the column expression(s) provided.
  • asc | desc: These optional parameters are used to specify whether the sorting of rows within each partition would be in ascending or descending order. ‘ASC’ for ascending order and ‘DESC’ for descending order. If no option is provided, the default is ‘ASC’.
  • [, …]: This represents that multiple column expressions can be provided for ‘PARTITION BY’ and ‘ORDER BY’.
WITH Scores AS (
SELECT student_id, score
FROM Exam
)
SELECT student_id, score, NTILE(4) OVER (ORDER BY score DESC) AS quartile
FROM Scores;
student_idscorequartile
1981
2951
3922
4902
5853
6823
7754
8704

In the given example, the NTILE function is used to divide the exam scores of students into four groups or quartiles ordered by score in descending order. The groups are approximately of equal size. The function will assign a quartile value (1-4) based on the score percentile of each student.