![]() |
VOOZH | about |
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.
The 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.
The syntax of the NTILE() looks like below:
NTILE(buckets) OVER ( [PARTITION BY partition_expression, ... ] [ORDER BY sort_expression [ASC | DESC], ...] )
Let's analyze the above syntax:
Let's look into some practical examples to understand how the NTILE() function works in PostgreSQL.
First, create a table named 'sales_stats' that stores the sales revenue by employees:
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:
👁 PostgreSQL NTILE() Function ExampleExplanation: The NTILE() function divides the rows into three buckets based on the 'amount' column for the year 2019.
The 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:
👁 PostgreSQL NTILE() Function ExampleExplanation: 'PARTITION BY year' divides 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.