Last Updated : 15 Jul, 2025
In PostgreSQL, the NTILE() function is a powerful tool used to divide ordered rows into a specified number of ranked buckets, which are essentially ranked groups. This function is crucial for data analysis and reporting, allowing users to efficiently distribute rows and analyze data in a structured manner.
Let us get a better understanding of the NTILE Function in PostgreSQL from this article.
NTILE() Function in PostgreSQLThe NTILE() function partitions data into a specified number of buckets. Each bucket contains a roughly equal number of rows. This function is particularly useful for creating quantiles, percentiles, and other ranked groupings.
SyntaxThe syntax of the NTILE() looks like below:
NTILE(buckets) OVER ( [PARTITION BY partition_expression, ... ] [ORDER BY sort_expression [ASC | DESC], ...] )Parameters
Let's analyze the above syntax:
Let's look into some practical examples to understand how the NTILE() function works in PostgreSQL.
Example 1: Distributing Rows into BucketsFirst, create a table named 'sales_stats' that stores the sales revenue by employees:
PostgreSQL
CREATE TABLE sales_stats(
name VARCHAR(100) NOT NULL,
year SMALLINT NOT NULL CHECK (year > 0),
amount DECIMAL(10, 2) CHECK (amount >= 0),
PRIMARY KEY (name, year)
);
INSERT INTO
sales_stats(name, year, amount)
VALUES
('Raju kumar', 2018, 120000),
('Alibaba', 2018, 110000),
('Gabbar Singh', 2018, 150000),
('Kadar Khan', 2018, 30000),
('Amrish Puri', 2018, 200000),
('Raju kumar', 2019, 150000),
('Alibaba', 2019, 130000),
('Gabbar Singh', 2019, 180000),
('Kadar Khan', 2019, 25000),
('Amrish Puri', 2019, 270000);
Now, use the NTILE() function to distribute rows into 3 buckets for the year 2019:
Query:
SELECT name, amount, NTILE(3) OVER( ORDER BY amount ) FROM sales_stats WHERE year = 2019;
Output:
Explanation: The NTILE() function divides the rows into three buckets based on the 'amount' column for the year 2019.
Example 2: Dividing Rows into Partitions and BucketsThe below query uses the NTILE() function to divide rows in the 'sales_stats' table into two partitions and 3 buckets for each.
Query:
SELECT name, amount, NTILE(3) OVER( PARTITION BY year ORDER BY amount ) FROM sales_stats;
Output:
Explanation: 'PARTITION BY year'
d
ivides the rows into partitions based on the year. The 'ORDER BY amount'
Sorts the rows within each partition by the amount
column and the NTILE(3)
distributes rows into three buckets within each partition.
- NTILE() allows flexible grouping of data into buckets based on specified criteria.
- The function can partition data using the PARTITION BY clause, allowing for more granular analysis.
- The buckets parameter must be a positive integer or an expression that evaluates to a positive integer.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4