SQL NTILE
Split ordered rows into n roughly equal groups (quartiles, deciles).
Syntax
NTILE(n) OVER (ORDER BY …)
Example
Query (on the shop database used in the SQL course)
SELECT name, price, NTILE(4) OVER (ORDER BY price) AS price_quartile FROM products;
Result
| name | price | price_quartile |
|---|---|---|
| A5 notebook | 8.5 | 1 |
| Gel pens, pack of 10 | 11.0 | 1 |
| Green tea, 100 bags | 12.0 | 1 |
| SQL Pocket Guide | 25.0 | 1 |
| Wireless mouse | 29.0 | 2 |
| Coffee beans 1 kg | 32.0 | 2 |
| Python Crash Course (book) | 45.0 | 2 |
| USB-C hub | 49.0 | 2 |
| Desk lamp | 59.0 | 3 |
| Deep Learning (book) | 89.0 | 3 |
| Mechanical keyboard | 119.0 | 3 |
| Noise-cancelling headphones | 249.0 | 3 |
| 27-inch monitor | 329.0 | 4 |
| Ergonomic chair | 399.0 | 4 |
| Standing desk | 549.0 | 4 |
15 rows
Related
Learn it step by step in the free lesson CTEs & Window Functions, with exercises that check your queries.