Bird
0
0

How would you modify this query to rank students by score within each class, but ensure no gaps in ranks?

hard📝 Application Q9 of 15
PostgreSQL - Window Functions in PostgreSQL
How would you modify this query to rank students by score within each class, but ensure no gaps in ranks?
SELECT student_id, class_id, RANK() OVER (PARTITION BY class_id ORDER BY score DESC) AS rank FROM students;
AAdd ROW_NUMBER() instead of RANK()
BReplace RANK() with DENSE_RANK()
CRemove PARTITION BY clause
DUse COUNT() OVER instead of RANK()
Step-by-Step Solution
Solution:
  1. Step 1: Identify issue with RANK() gaps

    RANK() leaves gaps in ranking when ties occur.
  2. Step 2: Use DENSE_RANK() to avoid gaps

    DENSE_RANK() assigns consecutive ranks without gaps within each partition.
  3. Final Answer:

    Replace RANK() with DENSE_RANK() -> Option B
  4. Quick Check:

    DENSE_RANK removes gaps in partitioned ranking = Replace RANK() with DENSE_RANK() [OK]
Quick Trick: Use DENSE_RANK() for gapless ranks within groups [OK]
Common Mistakes:
  • Using ROW_NUMBER() which ignores ties
  • Removing PARTITION BY causing wrong grouping
  • Using COUNT() which is unrelated

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes