Bird
Raised Fist0
PostgreSQLquery~5 mins

ROW_NUMBER, RANK, DENSE_RANK in PostgreSQL

Choose your learning style10 modes available
Introduction

These functions help you number or rank rows in a table based on some order. They make it easy to find positions or ranks of items.

When you want to assign a unique number to each row in a sorted list, like numbering students by their scores.
When you want to find the rank of items where ties get the same rank but skip numbers after, like ranking runners in a race.
When you want to rank items with ties but without skipping numbers, like ranking salespeople with equal sales.
When you need to paginate results and want to number rows for each page.
When you want to compare positions of items within groups, like ranking employees by department.
Syntax
PostgreSQL
ROW_NUMBER() OVER (ORDER BY column1 [ASC|DESC])
RANK() OVER (ORDER BY column1 [ASC|DESC])
DENSE_RANK() OVER (ORDER BY column1 [ASC|DESC])

These are window functions used with the OVER() clause.

ORDER BY inside OVER() defines how rows are sorted before numbering or ranking.

Examples
Assigns a unique row number to players ordered by score from highest to lowest.
PostgreSQL
SELECT name, score, ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num FROM players;
Ranks players by score. Players with the same score get the same rank, but ranks skip numbers after ties.
PostgreSQL
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM players;
Ranks players by score. Players with the same score get the same rank, and ranks do not skip numbers after ties.
PostgreSQL
SELECT name, score, DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank FROM players;
Sample Program

This example creates a small table of players with scores. It then shows how each function numbers or ranks the players ordered by score descending.

PostgreSQL
CREATE TEMP TABLE players (name TEXT, score INT);
INSERT INTO players VALUES
('Alice', 90),
('Bob', 95),
('Charlie', 90),
('David', 85);

SELECT name, score,
  ROW_NUMBER() OVER (ORDER BY score DESC) AS row_number,
  RANK() OVER (ORDER BY score DESC) AS rank,
  DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank
FROM players
ORDER BY score DESC, name;
OutputSuccess
Important Notes

ROW_NUMBER always gives a unique number, even if values tie.

RANK skips numbers after ties, so ranks can jump (e.g., 1, 2, 2, 4).

DENSE_RANK does not skip numbers after ties (e.g., 1, 2, 2, 3).

Summary

Use ROW_NUMBER to give each row a unique position.

Use RANK to assign ranks with gaps after ties.

Use DENSE_RANK to assign ranks without gaps after ties.

Practice

(1/5)
1. What does the ROW_NUMBER() function do in PostgreSQL?
easy
A. Counts the total number of rows in the table.
B. Assigns the same rank to rows with identical values, skipping ranks after ties.
C. Assigns ranks to rows without skipping numbers after ties.
D. Assigns a unique sequential number to each row in the result set.

Solution

  1. Step 1: Understand ROW_NUMBER() purpose

    ROW_NUMBER() gives each row a unique sequential number, starting at 1.
  2. Step 2: Compare with RANK() and DENSE_RANK()

    Unlike RANK() or DENSE_RANK(), ROW_NUMBER() never assigns the same number to multiple rows.
  3. Final Answer:

    Assigns a unique sequential number to each row in the result set. -> Option D
  4. Quick Check:

    ROW_NUMBER() = unique row numbers [OK]
Hint: ROW_NUMBER always gives unique numbers, no ties allowed [OK]
Common Mistakes:
  • Confusing ROW_NUMBER with RANK or DENSE_RANK
  • Thinking ROW_NUMBER skips numbers after ties
  • Assuming ROW_NUMBER counts total rows
2. Which of the following is the correct syntax to assign a rank using RANK() over a column named score ordered descending?
easy
A. SELECT RANK(score) OVER (ORDER BY DESC) FROM table_name;
B. SELECT RANK() ORDER BY score DESC FROM table_name;
C. SELECT RANK() OVER (ORDER BY score DESC) FROM table_name;
D. SELECT RANK() OVER (PARTITION BY score DESC) FROM table_name;

Solution

  1. Step 1: Recall correct RANK() syntax

    RANK() is used with OVER() clause specifying ORDER BY column and direction.
  2. Step 2: Check each option

    SELECT RANK() OVER (ORDER BY score DESC) FROM table_name; correctly uses RANK() OVER (ORDER BY score DESC). Others misuse syntax or clauses.
  3. Final Answer:

    SELECT RANK() OVER (ORDER BY score DESC) FROM table_name; -> Option C
  4. Quick Check:

    RANK() OVER (ORDER BY column DESC) syntax [OK]
Hint: RANK() needs OVER with ORDER BY column [OK]
Common Mistakes:
  • Putting column inside RANK() function
  • Using PARTITION BY incorrectly
  • Omitting OVER() clause
3. Given the table players with columns name and score, what will be the output of this query?
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM players;

Data:
name | score -----|------ Alice | 100 Bob | 90 Carol | 90 Dave | 80
medium
A. [{"name": "Alice", "score": 100, "rank": 1}, {"name": "Bob", "score": 90, "rank": 1}, {"name": "Carol", "score": 90, "rank": 1}, {"name": "Dave", "score": 80, "rank": 2}]
B. [{"name": "Alice", "score": 100, "rank": 1}, {"name": "Bob", "score": 90, "rank": 2}, {"name": "Carol", "score": 90, "rank": 2}, {"name": "Dave", "score": 80, "rank": 4}]
C. [{"name": "Alice", "score": 100, "rank": 1}, {"name": "Bob", "score": 90, "rank": 2}, {"name": "Carol", "score": 90, "rank": 2}, {"name": "Dave", "score": 80, "rank": 3}]
D. [{"name": "Alice", "score": 100, "rank": 1}, {"name": "Bob", "score": 90, "rank": 2}, {"name": "Carol", "score": 90, "rank": 3}, {"name": "Dave", "score": 80, "rank": 4}]

Solution

  1. Step 1: Understand RANK() behavior with ties

    RANK() assigns the same rank to tied scores and skips ranks after ties.
  2. Step 2: Apply ranks to scores

    Alice has highest score 100 -> rank 1. Bob and Carol tie at 90 -> both rank 2. Next rank after tie skips to 4 for Dave.
  3. Final Answer:

    [{"name": "Alice", "score": 100, "rank": 1}, {"name": "Bob", "score": 90, "rank": 2}, {"name": "Carol", "score": 90, "rank": 2}, {"name": "Dave", "score": 80, "rank": 4}] -> Option B
  4. Quick Check:

    RANK() skips ranks after ties [OK]
Hint: RANK() skips numbers after ties, DENSE_RANK() does not [OK]
Common Mistakes:
  • Assuming ranks after ties are consecutive
  • Confusing RANK() with DENSE_RANK()
  • Misordering rows by score
4. Identify the error in this query:
SELECT name, DENSE_RANK(score) OVER (ORDER BY score DESC) FROM players;
medium
A. DENSE_RANK() should not have a column inside the parentheses.
B. DENSE_RANK() cannot be used without PARTITION BY clause.
C. ORDER BY clause is missing in the OVER() clause.
D. The query is correct and will run without errors.

Solution

  1. Step 1: Check DENSE_RANK() syntax

    DENSE_RANK() does not take any arguments inside parentheses; it is called as DENSE_RANK() OVER (...).
  2. Step 2: Identify the error in the query

    The query incorrectly uses DENSE_RANK(score), which causes a syntax error.
  3. Final Answer:

    DENSE_RANK() should not have a column inside the parentheses. -> Option A
  4. Quick Check:

    DENSE_RANK() has empty parentheses [OK]
Hint: Window functions have empty parentheses, column goes in ORDER BY [OK]
Common Mistakes:
  • Putting column inside DENSE_RANK()
  • Thinking PARTITION BY is mandatory
  • Omitting OVER() clause
5. You want to assign ranks to employees based on their sales, but you want no gaps in ranking numbers even if some employees have the same sales. Which function should you use and why?

Options:
A) ROW_NUMBER() because it gives unique numbers.
B) RANK() because it skips ranks after ties.
C) DENSE_RANK() because it assigns ranks without gaps after ties.
D) COUNT() because it counts rows.
hard
A. DENSE_RANK() because it assigns ranks without gaps after ties.
B. RANK() because it skips ranks after ties.
C. ROW_NUMBER() because it gives unique numbers.
D. COUNT() because it counts rows.

Solution

  1. Step 1: Understand ranking requirements

    The requirement is to assign ranks with no gaps even if employees tie in sales.
  2. Step 2: Match functions to behavior

    ROW_NUMBER() gives unique numbers, ignoring ties. RANK() skips ranks after ties causing gaps. DENSE_RANK() assigns ranks without gaps after ties.
  3. Step 3: Choose correct function

    DENSE_RANK() fits the requirement perfectly.
  4. Final Answer:

    DENSE_RANK() because it assigns ranks without gaps after ties. -> Option A
  5. Quick Check:

    DENSE_RANK() = no gaps in ranks [OK]
Hint: Use DENSE_RANK() to avoid gaps in ranking numbers [OK]
Common Mistakes:
  • Choosing RANK() and expecting no gaps
  • Using ROW_NUMBER() which ignores ties
  • Confusing COUNT() with ranking functions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard