Rank and total rows with window functions

PostgreSQL 19.0

A CTE can name the result of an intermediate step, such as enrollment counts by course. Sometimes the result must keep the individual rows as well as a total or rank. Window functions calculate across related rows while keeping one output row for each input row.

On this page

Keep each row in a running total

PARTITION BY creates independent groups. ORDER BY inside OVER controls the calculation order, and the explicit ROWS frame ends at the current row. The final ORDER BY controls display order.

SELECT course_id, student_id, enrolled_on,
       COUNT(*) OVER (
         PARTITION BY course_id
         ORDER BY enrolled_on, student_id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS enrollments_so_far
FROM enrollments
ORDER BY course_id, enrolled_on, student_id;

Choose how to handle ties

row_number gives each row its own number. rank gives tied rows the same rank and leaves gaps. dense_rank gives tied rows the same rank without gaps. Add a tie-breaker when you need a repeatable row_number for equal values.

WITH scores (name, score) AS (
  VALUES ('Taylor', 95), ('Jamie', 95), ('Casey', 90)
)
SELECT name, score,
       row_number() OVER (ORDER BY score DESC, name) AS row_number,
       rank()       OVER (ORDER BY score DESC) AS rank,
       dense_rank() OVER (ORDER BY score DESC) AS dense_rank
FROM scores
ORDER BY row_number;

Official references