๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the department with the highest average salary.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC
LIMIT 1;
๐ก Explanation:
The query calculates the average salary for each department and returns the department with the highest average salary.
โข GROUP BY department groups employees by department
โข AVG(salary) calculates the average salary for each department
โข ORDER BY average_salary DESC sorts departments from highest to lowest average salary
โข LIMIT 1 returns only the top department
This question tests your understanding of:
โ
GROUP BY
โ
Aggregate Functions AVG
โ
ORDER BY
โ
LIMIT
๐ฏ Expected Output
Department Average_Salary
IT 88,500
๐ Bonus Handles Ties
If multiple departments share the highest average salary, use DENSE_RANK():
SELECT
department,
average_salary
FROM (
SELECT
department,
AVG(salary) AS average_salary,
DENSE_RANK() OVER (
ORDER BY AVG(salary) DESC
) AS rnk
FROM employees
GROUP BY department
) ranked
WHERE rnk = 1;
This version returns all departments tied for the highest average salary.
๐ Whenever you see questions like highest, lowest, top N, or rank, think beyond LIMIT. Ask yourself: What if there's a tie? Window functions like DENSE_RANK() often provide a more complete solution.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2900
4.26K
- โค 15