How to Use The Percentile Functions in PostgreSQL

When working with large datasets, finding the average is not always enough to understand how values are distributed. Percentiles provide a better way to analyze data by showing the value below which a specific percentage of records fall. They are commonly used to calculate metrics such as the median, response time percentiles, salary distributions, and other statistical summaries.

PostgreSQL includes built-in percentile functions that support both continuous and discrete percentile calculations. These functions can work with numeric values, intervals, dates, and other sortable data types, making them useful for performance analysis, business reporting, and data analytics.

In this article, we'll explore every percentile-related function available in PostgreSQL. You'll learn how to list these functions from the pg_catalog schema, understand the purpose of each one, and see practical examples of using percentile_cont and percentile_disc to calculate median values, multiple percentiles, and quartiles.

In postgres, we can check the names of the functions that start with percentile by using the below command like this.

Enter the percentile keyword and press the Tab key to list the names.

postgres=# \df+ percentile_

Result:

percentile_cont                       percentile_cont_float8_multi_final    percentile_cont_interval_multi_final  percentile_disc_final                 
percentile_cont_float8_final          percentile_cont_interval_final        percentile_disc                       percentile_disc_multi_final 

We can inspect each function's metadata by using the \df+ command like this.

1.percentile_cont

postgres=# \df+ percentile_cont

Result:

List of functions
-[ RECORD 1 ]-------+---------------------------------------------
Schema              | pg_catalog
Name                | percentile_cont
Result data type    | double precision
Argument data types | double precision ORDER BY double precision
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | continuous distribution percentile
-[ RECORD 2 ]-------+---------------------------------------------
Schema              | pg_catalog
Name                | percentile_cont
Result data type    | double precision[]
Argument data types | double precision[] ORDER BY double precision
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | multiple continuous percentiles
-[ RECORD 3 ]-------+---------------------------------------------
Schema              | pg_catalog
Name                | percentile_cont
Result data type    | interval
Argument data types | double precision ORDER BY interval
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | continuous distribution percentile
-[ RECORD 4 ]-------+---------------------------------------------
Schema              | pg_catalog
Name                | percentile_cont
Result data type    | interval[]
Argument data types | double precision[] ORDER BY interval
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | multiple continuous percentiles

2.percentile_cont_float8_final

postgres=# \df+ percentile_cont_float8_final

Result:

List of functions
-[ RECORD 1 ]-------+-----------------------------
Schema              | pg_catalog
Name                | percentile_cont_float8_final
Result data type    | double precision
Argument data types | internal, double precision
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_cont_float8_final
Description         | aggregate final function

3.percentile_cont_float8_multi_final

postgres=# \df+ percentile_cont_float8_multi_final

Result:

List of functions
-[ RECORD 1 ]-------+-----------------------------------
Schema              | pg_catalog
Name                | percentile_cont_float8_multi_final
Result data type    | double precision[]
Argument data types | internal, double precision[]
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_cont_float8_multi_final
Description         | aggregate final function

4. percentile_cont_interval_final

postgres=# \df+ percentile_cont_interval_final

Result:

List of functions
-[ RECORD 1 ]-------+-------------------------------
Schema              | pg_catalog
Name                | percentile_cont_interval_final
Result data type    | interval
Argument data types | internal, double precision
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_cont_interval_final
Description         | aggregate final function

5. percentile_cont_interval_multi_final

postgres=# \df+ percentile_cont_interval_multi_final

Result:

List of functions
-[ RECORD 1 ]-------+-------------------------------------
Schema              | pg_catalog
Name                | percentile_cont_interval_multi_final
Result data type    | interval[]
Argument data types | internal, double precision[]
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_cont_interval_multi_final
Description         | aggregate final function

6. percentile_disc

postgres=# \df+ percentile_disc

Result:

List of functions
-[ RECORD 1 ]-------+---------------------------------------
Schema              | pg_catalog
Name                | percentile_disc
Result data type    | anyelement
Argument data types | double precision ORDER BY anyelement
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | discrete percentile
-[ RECORD 2 ]-------+---------------------------------------
Schema              | pg_catalog
Name                | percentile_disc
Result data type    | anyarray
Argument data types | double precision[] ORDER BY anyelement
Type                | agg
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | aggregate_dummy
Description         | multiple discrete percentiles

7. percentile_disc_final

postgres=# \df+ percentile_disc_final

Result:

List of functions
-[ RECORD 1 ]-------+---------------------------------------
Schema              | pg_catalog
Name                | percentile_disc_final
Result data type    | anyelement
Argument data types | internal, double precision, anyelement
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_disc_final
Description         | aggregate final function

8. percentile_disc_multi_final

postgres=# \df+ percentile_disc_multi_final

Result:

List of functions
-[ RECORD 1 ]-------+-----------------------------------------
Schema              | pg_catalog
Name                | percentile_disc_multi_final
Result data type    | anyarray
Argument data types | internal, double precision[], anyelement
Type                | func
Volatility          | immutable
Parallel            | safe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | internal
Internal name       | percentile_disc_multi_final
Description         | aggregate final function

Here, we can see nearly 8 percentile-related functions, but we can only use two: percentile_cont and percentile_disc. The other functions are internal functions that are used internally, and cannot be used directly.

In each function definition, the language column, and that column indicates whether the function is an internal function or not.

Query Examples:

Create a sample table for testing.

CREATE TABLE emp_perf (
    emp_id         SERIAL PRIMARY KEY,
    emp_name       TEXT,
    salary         INTEGER,
    hire_date      DATE,
    response_time  INTERVAL
);

Insert some sample values.

INSERT INTO emp_perf (emp_name, salary, hire_date, response_time) VALUES('Akhil',    45000, '2018-01-10', '00:03:30'),('Anu',      48000, '2019-03-15', '00:05:00'),('Rahul',    50000, '2019-08-20', '00:06:30'),('Sneha',    55000, '2020-01-05', '00:07:00'),('Faisal',   62000, '2020-10-10', '00:08:00'),('Meera',    70000, '2021-06-18', '00:09:00'),('Arun',     80000, '2022-02-14', '00:12:00'),('Nithya',   85000, '2022-09-01', '00:15:00'),('Vivek',    90000, '2023-04-12', '00:20:00'),('Lakshmi',  95000, '2024-01-08', '00:25:00');

Now, use the percentile_cont() function like this.

The percentile_cont() returns the exact percentile by interpolating between values when necessary. As a result, it can return a value that is not present in the dataset.

SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM emp_perf;

Result:

median_salary 
---------------
         66000
(1 row)

This query returns the 50th percentile (median) of the salary column from the emp_perf table using the percentile_cont() function.

Now, try the SELECT query with two percentile_cont() like this.

SELECT percentile_cont(0.5)  WITHIN GROUP (ORDER BY response_time) AS median_response,
       percentile_cont(0.95) WITHIN GROUP (ORDER BY response_time) AS p95_response
FROM emp_perf;

Result:

 median_response | p95_response 
-----------------+--------------
 00:08:30        | 00:22:45
(1 row)

This query calculates two percentiles for the response_time column in the emp_perf table using the percentile_cont() function. It returns the 50th percentile (median) as median_response and the 95th percentile as p95_response.

Now, pass an array of values to percentile_cont() like this.

SELECT percentile_cont(ARRAY[0.25, 0.5, 0.75]) WITHIN GROUP (ORDER BY salary) AS salary_quartiles
FROM emp_perf;

Result:

  salary_quartiles   
---------------------
 {51250,66000,83750}
(1 row)

This query calculates multiple percentiles of the salary column from the emp_perf table using the percentile_cont() function. Instead of calculating a single percentile, it passes an array of percentile values.

Now, use percentile_disc() with a SELECT query like this.

The percentile_disc() returns the percentile as an existing value from the dataset. It always chooses an actual value and never returns an interpolated one.

SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY salary)        AS median_salary_disc,
       percentile_disc(0.5) WITHIN GROUP (ORDER BY hire_date)     AS median_hire_date,
       percentile_disc(0.5) WITHIN GROUP (ORDER BY emp_name)      AS median_name,
       percentile_disc(0.5) WITHIN GROUP (ORDER BY response_time) AS median_response_disc
FROM emp_perf;

Result:

 median_salary_disc | median_hire_date | median_name | median_response_disc 
--------------------+------------------+-------------+----------------------
              62000 | 2020-10-10       | Lakshmi     | 00:08:00
(1 row)

This query calculates the 50th percentile (median) for multiple columns in the emp_perf table using the percentile_disc() function.

Unlike percentile_cont(), the percentile_disc() function always returns an existing value from the dataset. It does not interpolate between values.

Now, pass an array of values to the percentile_disc() function like this.

SELECT percentile_disc(ARRAY[0.25, 0.5, 0.75]) WITHIN GROUP (ORDER BY hire_date) AS hire_date_quartiles
FROM emp_perf;

Result:

       hire_date_quartiles         
------------------------------------
 {2019-08-20,2020-10-10,2022-09-01}
(1 row)

This query calculates the 25th, 50th, and 75th percentiles (quartiles) of the hire_date column in the emp_perf table using the percentile_disc() function.

PostgreSQL provides a complete set of percentile functions for analyzing ordered data. While percentile_cont calculates values using continuous interpolation and percentile_disc returns actual values from the dataset, the remaining functions with names ending in _final and _multi_final are internal aggregate final functions that PostgreSQL uses during query execution. These internal functions support the implementation of the public aggregate functions and are not intended to be called directly in SQL queries.

By understanding the purpose of each function and knowing when to use continuous or discrete percentile calculations, you can generate more meaningful statistical insights from your data. Whether you're calculating median salaries, response-time percentiles, quartiles, or other distribution-based metrics, PostgreSQL's built-in percentile functions provide an efficient and reliable solution for analytical queries.

WhatsApp