![]() |
VOOZH | about |
SQL NTILE() function is a window function that distributes rows of an ordered partition into a pre-defined number of roughly equal groups.
The NTILE() function in SQL server is used to distribute rows of an ordered partition into a specified number of approximately equal groups, or buckets.
It assigns each group a number_expression ranging from one. NTILE() function assigns a number_expression for every row in a group, to which the row belongs.
The NTILE() function syntax is:
NTILE(number_expression) OVER ( [PARTITION BY partition_expression ] ORDER BY sort_expression [ASC | DESC])
When a number of rows aren't divisible by the number_expression, the NTILE() function results the groups of two sizes with a difference by one. The larger groups always come ahead of the smaller group within the order specified by the ORDER BY within the OVER() clause. Also, when the all of rows are divisible by the number_expression, the function divides evenly the rows among number_expression.
Let's look at some examples of NTILE() function in SQL Server to understand it better.
First we will create a table named 'geeks_demo'
Query:
CREATE TABLE geeks_demo (
ID INT NOT NULL );
INSERT INTO geeks_demo(ID)
VALUES(1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
Output:
| ID |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
Query:
SELECT ID,
NTILE (3) OVER (
ORDER BY ID
) Group_number
FROM geeks_demo;
Output :
| ID | Group_number |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 2 |
| 7 | 2 |
| 8 | 3 |
| 9 | 3 |
| 10 | 3 |
Query:
SELECT ID,
NTILE (5) OVER (
ORDER BY ID
) Group_number
FROM geeks_demo;
Output :
| ID | Group_number |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 3 |
| 6 | 3 |
| 7 | 4 |
| 8 | 4 |
| 9 | 5 |
| 10 | 5 |
SELECT ID,
NTILE () OVER (
ORDER BY ID
) Group_number
FROM geeks_demo;
Output: It will throw the below error:
The function 'NTILE' takes exactly 1 argument(s).
- The NTILE() function is a window function that distributes rows of an ordered partition into a specified number of approximately equal groups, or buckets.
- It assigns each group a bucket number starting from one.
- If the total of rows is divisible by the
buckets, the function divides evenly the rows among buckets.- If the number of rows is not divisible by the
buckets, the NTILE() function returns groups of two sizes with the difference by one.- Proper indexing on columns used in the
ORDER BYclause within theOVER()partition can improve performance when using NTILE() on large datasets- It is useful for creating histograms, analyzing rankings, or dividing data to allow parallel processing.