cume_dist
PG 8.4+→ double precisionReturns the cumulative distribution of the current row: proportion of rows with values <= current row's value. Result is always in (0, 1].
Signature
cume_dist ( ) → double precisionExamples
SELECT name, score, cume_dist() OVER (ORDER BY score) AS cdf FROM results;Fraction of rows scoring <= this rowSELECT * FROM results WHERE cume_dist() OVER (ORDER BY score DESC) <= 0.1;Top 10% of scoresSELECT employee_id, salary, round((cume_dist() OVER (ORDER BY salary) * 100)::numeric, 1) AS salary_percentile FROM employees;What percentage of employees earn at or below this salarySELECT product_id, revenue, cume_dist() OVER (PARTITION BY category ORDER BY revenue) AS category_cdf FROM sales;Cumulative revenue distribution within each categoryYou cannot use cume_dist() (or any window function) directly in a WHERE clause. Wrap the query in a CTE or subquery first.
✓ Instead: WITH dist AS (SELECT *, cume_dist() OVER (ORDER BY lifetime_value DESC) AS cd FROM customers) SELECT * FROM dist WHERE cd <= 0.05;
Use `cume_dist() OVER (ORDER BY score DESC) <= 0.1` to select the top 10% without pre-computing the 90th percentile threshold. This adapts automatically as data changes.
SELECT * FROM customers WHERE cume_dist() OVER (ORDER BY lifetime_value DESC) <= 0.05;Top 5% of customers by lifetime value