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
Syntax
dense_rank() OVER (PARTITION BY ... ORDER BY ...)
Return value
bigint.
Examples
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.
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
| Version | Change |
|---|---|
| PostgreSQL 8.4 | Added |
In other languages
DENSE_RANK()· SQLite
Related
RANK()· Rank rows by ORDER BY, giving ties the same rank and leaving gaps after them (1, 2, 2, 4).ROW_NUMBER()· Number the rows of each window partition 1, 2, 3, … in ORDER BY order. Ties get different numbers.- SQL Window Functions · tutorial