HomeInterview QuestionsWrite an SQL query that joins the Employee and Dep…

Write an SQL query that joins the Employee and Department tables to display employee name, department name, and salary, and then uses a window function to rank employees by salary within each department.

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

💡 Model Answer

First perform the join, then apply ROW_NUMBER() to rank employees per department:

sql
SELECT e.emp_name,
       d.dept_name,
       e.salary,
       ROW_NUMBER() OVER (PARTITION BY d.dept_name
                          ORDER BY e.salary DESC) AS dept_rank
FROM   Employee e
JOIN   Department d
       ON e.dept_id = d.dept_id;

The query returns each employee with their department and salary, plus a rank that starts at 1 for the highest‑paid employee in each department. The join is O(n) and the window function adds O(n log n) due to the internal sort, which is acceptable for most workloads. If you only need the top N per department, add a WHERE clause on dept_rank.

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