> ## Documentation Index
> Fetch the complete documentation index at: https://docs.e6data.com/llms.txt
> Use this file to discover all available pages before exploring further.

# NTILE

> Divides the ordered rows in each group into buckets as evenly as possible.

<div className="e6-meta"><span className="e6-eyebrow e6-eyebrow--quiet">Window function</span></div>

Returns a non-NULL bucket number for each row. Invalid or NULL bucket counts raise an error.

## Syntax

A window function keeps each input row and adds a result for that row. `PARTITION BY` groups rows with matching values; without it, all input rows form one group.

### Window

```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
ntile(buckets) OVER ([PARTITION BY key] ORDER BY ordering_key [ROWS frame])
```

* NTILE assigns buckets using all ordered rows in each group. A ROWS frame clause does not change the buckets. RANGE frames with numeric or time offsets are not supported.

## Arguments

| Name | Type | Required | Description |
| - | - | - | - |
| buckets | positive integer literal | Yes | Number of buckets. Greater than zero; NULL, zero and negative values are rejected. Must be a constant argument. |

## Returns

* Type: BIGINT
* Possible values: 1 through min(buckets, number of rows in the group).
* NULL behavior: Returns a non-NULL bucket number for each row. Invalid or NULL bucket counts raise an error.
* Empty input: An empty input produces no rows.

## Properties

| Property | Value |
| - | - |
| Deterministic | Partial (Use unique ORDER BY values when assigning stable rows to buckets.) |
| Supports window usage | Yes |
| Supports window frames | Partial (A frame clause has no effect on bucket assignment. RANGE offsets are not supported.) |
| Exact result | Yes |

## Usage notes

* When rows do not divide evenly, the earliest buckets get one extra row.
* When there are more buckets than rows, only one bucket number per row is emitted.
* An explicit frame does not change NTILE’s bucket assignment. All rows in the PARTITION BY group are used.

## Examples

### Uneven bucket sizes

```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
WITH t("value") AS (VALUES (100), (90), (80), (70), (60), (50), (40), (30), (20), (10)) SELECT "value", ntile(4) OVER (ORDER BY "value" DESC) AS result FROM t ORDER BY "value" DESC;
```

| value | result |
| - | - |
| 100 | 1 |
| 90 | 1 |
| 80 | 1 |
| 70 | 2 |
| 60 | 2 |
| 50 | 2 |
| 40 | 3 |
| 30 | 3 |
| 20 | 4 |
| 10 | 4 |

### More buckets than rows

```sql theme={"theme":{"light":"github-light","dark":"github-dark"}}
WITH sample(id) AS (VALUES (1), (2), (3))
SELECT id, ntile(5) OVER (ORDER BY id) AS bucket FROM sample ORDER BY id;
```

| id | bucket |
| - | - |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.