SQL RANK

Ties share the same rank — and the rank after a tie jumps forward to account for it.

What & Why

RANK() gives tied rows the identical rank. The next row after a tie doesn't get the next consecutive number — it skips ahead by however many rows tied, so the ranks still add up to the row count.

See How It Works

BUSINESS QUESTION

Product wants feedback ratings ranked while preserving tied positions.

iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-04-08 17:30:00+00
Watch RANK preserve a tie and leave a gapStep 1 of 4
RANK() OVER (ORDER BY rating DESC)
feedback_idratingrating_rank
151
242
342
434

Rating 5 receives rank one.

EXAMPLE QUERY
SELECT
  id AS feedback_id,
  rating,
  RANK() OVER (ORDER BY rating DESC) AS rating_rank
FROM product.feedback
ORDER BY rating_rank, feedback_id;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario