SQL

NTILE — Bucket Rows into N Buckets

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Assign rows to N approximately-equal-sized buckets based on the ORDER BY. The standard way to compute quartiles, deciles, or any percentile bucket.
SQL
Raw
-- Split customers into quartiles by lifetime spend
SELECT user_id,
       total_spent,
       NTILE(4) OVER (ORDER BY total_spent DESC) AS spend_quartile
FROM   user_totals;

-- Each user's bucket → label
SELECT user_id,
       CASE NTILE(4) OVER (ORDER BY total_spent DESC)
         WHEN 1 THEN 'platinum'
         WHEN 2 THEN 'gold'
         WHEN 3 THEN 'silver'
         WHEN 4 THEN 'bronze'
       END AS tier
FROM   user_totals;

-- Deciles within each category
SELECT product, price,
       NTILE(10) OVER (PARTITION BY category ORDER BY price) AS price_decile
FROM   products;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.