PostgreSQL PERCENT_RANK Function (original) (raw)

Last Updated : 15 Jul, 2025

In **PostgreSQL, the **PERCENT_RANK() function is used to evaluate the relative ranking of a value within a given set of values. This function is particularly useful for statistical analysis and reporting, providing insights into how values compare within a dataset.

From this article, we can better understand the **PERCENT_RANK Function in **PostgreSQL.

**Syntax

The syntax of the **PERCENT_RANK() function:

**PERCENT_RANK() **OVER ( [**PARTITION BY partition_expression, ... ] **ORDER BY sort_expression [**ASC | **DESC], ... )

Parameters

Let's analyze the above syntax:

Return Value

PostgreSQL PERCENT_RANK Function Examples

Let us take a look at some of the examples of **PERCENT_RANK **Function in **PostgreSQL from this article.

**Example 1: Using PERCENT_RANK() without PARTITION BY

First, create two tables named '**products' and '**product_groups':

PostgreSQL `

CREATE TABLE product_groups ( group_id serial PRIMARY KEY, group_name VARCHAR (255) NOT NULL );

CREATE TABLE products ( product_id serial PRIMARY KEY, product_name VARCHAR (255) NOT NULL, price DECIMAL (11, 2), group_id INT NOT NULL, FOREIGN KEY (group_id) REFERENCES product_groups (group_id) ); INSERT INTO product_groups (group_name) VALUES ('Smartphone'), ('Laptop'), ('Tablet');

INSERT INTO products (product_name, group_id, price) VALUES ('Microsoft Lumia', 1, 200), ('HTC One', 1, 400), ('Nexus', 1, 500), ('iPhone', 1, 900), ('HP Elite', 2, 1200), ('Lenovo Thinkpad', 2, 700), ('Sony VAIO', 2, 700), ('Dell Vostro', 2, 800), ('iPad', 3, 700), ('Kindle Fire', 3, 150), ('Samsung Galaxy Tab', 3, 200);

`

The following statement uses the **PERCENT_RANK() function to calculate the sales percentile of each employee in 2019.

**Query:

**SELECT name, amount, **PERCENT_RANK() OVER ( **ORDER BY amount ) **FROM sales_stats **WHERE year = 2019;

**Output:

**Explanation: This query calculates the percentile rank of each sales amount for the year 2019. The **ORDER BY clause orders the sales amounts, and PERCENT_RANK() assigns a percentile rank between 0 and 1 to each amount.

**Example 2: Using PERCENT_RANK() with PARTITION BY

The below statement uses the **PERCENT_RANK() function to calculate the sales amount percentile by sales employees in both 2018 and 2019.

**Query:

**SELECT name, amount, **PERCENT_RANK() **OVER ( PARTITION BY year **ORDER BY amount ) **FROM sales_stats;

**Output:

**Explanation: This query partitions the data by year, calculating the percentile rank of sales amounts within each year. The **PARTITION BY year clause ensures that the ranking is calculated separately for each year, providing a relative ranking within each partition.

Important Points About PostgreSQL PERCENT_RANK Function