PostgreSQL 18 reference · Window Functions

PostgreSQL DENSE_RANK() Function

Rank rows by ORDER BY, giving ties the same rank with no gaps after them (1, 2, 2, 3).

PostgreSQL 18 Since 8.4

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

dense_rank() OVER (PARTITION BY ... ORDER BY ...)

Return value

bigint.

Examples

rank() vs dense_rank()
SELECT name, title, rank() OVER w AS rank, dense_rank() OVER w AS dense
FROM employees
WHERE department = 'Engineering'
WINDOW w AS (ORDER BY title);

Output

     name     |        title        | rank | dense
--------------+---------------------+------+-------
 Omar Haddad  | CTO                 |    1 |     1
 Priya Nair   | Engineer            |    2 |     2
 Lucas Martin | Engineer            |    2 |     2
 Mei Chen     | Engineering Manager |    4 |     3
 Jonas Berg   | Senior Engineer     |    5 |     4
(5 rows)

Run this on your computer — see “Get Started” for setup.

Top three salary levels
SELECT DISTINCT salary, dense_rank() OVER (ORDER BY salary DESC) AS level
FROM employees
ORDER BY level
LIMIT 3;

Output

 salary | level
--------+-------
 250000 |     1
 210000 |     2
 165000 |     3
(3 rows)

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
PostgreSQL 8.4Added

In other languages

Was this page helpful?