facebook pixel
Day 4/7 - SQL Challenge 🎯 TODAY’S QUESTION: Rank employees by salary within each department. TABLE: Employees (id, name, department, salary) THE SOLUTION: SELECT name, department, salary, RANK() OVER ( PARTITION BY department ORDER BY salary DESC ) as salary_rank FROM Employees; BREAKDOWN: RANK() - Assigns ranking (1, 2, 3...) OVER - Defines the window PARTITION BY department - Separate ranking per department ORDER BY salary DESC - Highest salary = Rank 1 OUTPUT EXAMPLE: name | department | salary | salary_rank -β€”β€”β€”|β€”β€”β€”β€”|β€”β€”β€”|β€”β€”β€”β€” Alice | Sales | 90000 | 1 Bob | Sales | 80000 | 2 Charlie | Engineer | 95000 | 1 Diana | Engineer | 85000 | 2 RANK vs ROW_NUMBER vs DENSE_RANK: β€” RANK: 1, 2, 2, 4 (skips after tie) β€” DENSE_RANK: 1, 2, 2, 3 (no skip) β€” ROW_NUMBER: 1, 2, 3, 4 (no ties) WHEN TO USE EACH: RANK: When you want to skip ranks after ties DENSE_RANK: When you want consecutive ranks ROW_NUMBER: When you need unique numbers COMMON MISTAKES: ❌ Forgetting PARTITION BY (ranks acr...

Β 13.4k

Β 317

Β 9

Β 13.4k

    Suggested Credits
    Tags, Events, and Projects