// window reference

SQL NTILE for percentile buckets

NTILE(n) distributes partition rows as evenly as possible into n numbered buckets, a cheap percentile approximation that works everywhere window functions do.

카테고리
창
Returns
integer
In this category
15 of 79

구문

NTILE(4) OVER (ORDER BY x) | NTILE(10) OVER (PARTITION BY g ORDER BY x)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 MySQL 8.0+
SQLite 예 SQLite 3.25+
Oracle 예 Supported under this name.

예시

Any engine

SELECT customer_id, spend,
       NTILE(4) OVER (ORDER BY spend DESC) AS spend_quartile
FROM customers;

Any engine

-- deciles per region, then averages per bucket
WITH d AS (
  SELECT c.*, NTILE(10) OVER (PARTITION BY region ORDER BY spend DESC) AS decile
  FROM customers c
)
SELECT region, decile, AVG(spend) AS avg_spend
FROM d GROUP BY region, decile
ORDER BY region, decile;

알아 두면 좋은 정보

  • When rows do not divide evenly, earlier buckets get the extra row: 7 rows into 4 buckets is 2, 2, 2, 1. Do not assume equal bucket sizes.
  • NTILE buckets are by position, not by value: two rows with the same ORDER BY value can land in different buckets. For value-based percentiles use CUME_DIST or PERCENTILE_DISC.
  • NTILE requires ORDER BY; without it the bucketing is arbitrary.

Questions about NTILE for Percentiles

How is NTILE(100) different from a real percentile?

It ranks rows by position into 100 nearly-equal buckets, so a bucket can contain tied values and sizes differ by one. PERCENTILE_CONT/DISC answer 'what value is the median?'; NTILE answers 'which bucket is this row in?'.

Can the bucket count come from a variable or a column?

A variable or bind parameter works on all five. A column is where they split: SQL Server and MySQL reject it, Oracle accepts it only if it is a function of the PARTITION BY expressions (constant per partition), and PostgreSQL and SQLite accept it. Keep it constant per partition or the bucketing is meaningless.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.