Home › Interview Questions › Assign row numbers based on salary for each depart…

Assign row numbers based on salary for each department using a window function.

🟡 Medium Coding Junior level
1Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

To assign row numbers based on salary within each department, you can use the ROW_NUMBER() window function. The query partitions the data by department and orders each partition by salary (descending or ascending depending on your requirement). Example:

SELECT

department,

employee_id,

salary,

ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank

FROM employees;

This assigns 1 to the highest salary in each department, 2 to the next, and so on. The complexity is O(n) for the scan plus the cost of sorting each partition, which is typically O(n log n) overall. The window function is efficient because it processes each row once and uses the database's optimized sorting and partitioning mechanisms. If you need to handle ties, consider using RANK() or DENSE_RANK() instead of ROW_NUMBER().

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500