SQL NTILE

Splits ordered rows into a fixed number of roughly equal-sized buckets.

What & Why

NTILE(n) numbers rows from 1 through n after ordering them inside a window. It creates quartiles, deciles, and other relative segments when ranked groups are more useful than fixed thresholds.

See How It Works

BUSINESS QUESTION

Marketing divides campaigns into four spend tiers from highest to lowest.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT
  id AS campaign_id,
  name,
  spend,
  NTILE(4) OVER (ORDER BY spend DESC, id) AS spend_quartile
FROM marketing.campaigns
ORDER BY spend_quartile, spend DESC, campaign_id;
RESULT — four campaigns split into quartiles
campaign_idnamespendspend_quartile
4Enterprise Search60000.001
1Spring Launch55000.002
3Finance Retargeting50000.003
2Retention Webinar45000.004

With four input rows and four buckets, each campaign occupies one quartile.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario