Back to Developer Roadmap

Ntile Function

src/data/question-groups/sql-queries/content/ntile-function.md

4.01.6 KB
Original Source

NTILE() is a window function that divides rows into a pre-defined number of roughly equal groups. It's like breaking your data into different sets based on your defined criteria. For example, let's say you have some student scores from 1 to 100; you can use the NTILE() function to categorize the scores into different groups or buckets.

The syntax of the NTILE() function is:

sql
NTILE(n) OVER (ORDER BY some_column)
  • n: represents the number of groups you want to divide your rows into.
  • ORDER BY: defines the order of the rows in each group where the function is applied.

Let's see a practical example using a table Scores. The table stores students' scores on a test. We will see how to use the NTILE() function.

userIdscore
178
270
390
498
560
688
7100
866

The query using the NTILE() function looks like this:

sql
SELECT
  id,
  score,
  NTILE(3) OVER (ORDER BY score DESC) AS category
FROM scores;
userIdscorecategory
71001
4981
3901
6882
1782
2702
8663
5603

The NTILE() function is useful in data analysis because it can detect outliers in a data set and create histograms of data. It can also create percentiles and quartiles for data distribution.