Ranking Functions in PostgreSQL

From the PostgreSQL Advanced Features cheat sheet ยท Window Functions ยท verified Jul 2026

Ranking Functions

Assign ranks and row numbers to results

sql
-- ROW_NUMBER - Sequential numbers
SELECT 
  name,
  salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) as rank
FROM employees;

-- RANK - Same rank for ties, gaps in sequence
SELECT
  name,
  score,
  RANK() OVER (ORDER BY score DESC) as rank
FROM scores;

-- DENSE_RANK - Same rank for ties, no gaps
SELECT
  name,
  score, 
  DENSE_RANK() OVER (ORDER BY score DESC) as dense_rank
FROM scores;

-- DETAILED_TAB:
-- Ranking within groups (PARTITION BY)
SELECT
  department,
  name,
  salary,
  ROW_NUMBER() OVER (
    PARTITION BY department 
    ORDER BY salary DESC
  ) as dept_rank,
  RANK() OVER (
    ORDER BY salary DESC
  ) as company_rank
FROM employees;

-- NTILE - Divide into buckets
SELECT
  name,
  salary,
  NTILE(4) OVER (ORDER BY salary) as quartile
FROM employees;
๐ŸŸข Essential - Window functions are PostgreSQL's superpower
๐Ÿ’ก PARTITION BY is like GROUP BY for windows
๐Ÿ“Œ ROW_NUMBER always gives unique numbers
โšก Window functions often faster than subqueries
๐Ÿ”— Related: PERCENT_RANK, CUME_DIST for distributions
window-functionsranking

More PostgreSQL tasks

Back to the full PostgreSQL Advanced Features cheat sheet