Bird
0
0

How can you combine CTEs with window functions to find the rank of employees by salary within each department?

hard📝 Application Q9 of 15
PostgreSQL - Common Table Expressions
How can you combine CTEs with window functions to find the rank of employees by salary within each department?
AWindow functions cannot be used with CTEs
BApply RANK() inside the CTE without partitioning
CUse a CTE to select employees, then apply RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) in main query
DUse multiple CTEs without window functions
Step-by-Step Solution
Solution:
  1. Step 1: Understand window function usage

    RANK() with PARTITION BY groups employees by department and orders by salary.
  2. Step 2: Combine with CTE for clarity

    Using a CTE to select employees first, then applying RANK() in the main query, keeps logic clear and modular.
  3. Final Answer:

    Use a CTE to select employees, then apply RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) in main query -> Option C
  4. Quick Check:

    CTEs and window functions work together well = D [OK]
Quick Trick: Apply window functions after CTE for modular queries [OK]
Common Mistakes:
  • Applying RANK() without partitioning
  • Thinking window functions can't be used with CTEs
  • Using multiple unrelated CTEs unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes