SQL NTILE function
Distributes ordered rows into n numbered buckets as evenly as possible: NTILE(4) gives quartiles, NTILE(100) percentiles, by position rather than by value.
- Categoría
- Ventana
- Returns
integer- In this category
- 6 of 79
Sintaxis
NTILE(buckets) OVER (PARTITION BY g ORDER BY x)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | MySQL 8.0+ |
| SQLite | Sí | SQLite 3.25+ |
| Oracle | Sí | Supported under this name. |
Ejemplos
Any engine
SELECT name, spend,
NTILE(4) OVER (ORDER BY spend DESC) AS spend_quartile
FROM customers;
Any engine
SELECT region, spend,
NTILE(4) OVER (PARTITION BY region ORDER BY spend DESC) AS quartile
FROM customers;
Conviene saberlo
- Buckets are by row count, not by value: NTILE(2) over 1, 2, 3, 1000 puts 3 and 1000 in the same top bucket, and two equal values can land in different buckets. For value-based cut points use PERCENTILE_CONT or PERCENTILE_DISC.
- When rows do not divide evenly, earlier buckets get the extras: 10 rows in NTILE(4) sizes 3, 3, 2, 2.
- With fewer rows than buckets, some buckets are empty: NTILE(100) over 40 rows uses only buckets 1 to 40.
Questions about NTILE
What is the difference between NTILE and PERCENTILE_CONT?
NTILE buckets by row position: every bucket gets the same number of rows. PERCENTILE_CONT finds the value at a fraction of the ordered values. Uneven data gives different answers.
What happens when the rows do not divide evenly?
Earlier buckets absorb the remainder: 10 rows into 4 buckets sizes them 3, 3, 2, 2.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Deciles with NTILE Snippet
- Percentile buckets Snippet
- Find outliers with percentiles Snippet
- Build a value-distribution histogram Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.