Senior
-- There are tables with the following structure Employee id (PK) name salary dep_id(FK department.id) Department id (PK) name -- write a query that returns a list of all department names with the maximum salary in each department select d.name, MAX(e.salary) from Department d left join Employee e on e.dep_id = d.id group by d.name
sobes.tech AI
Answer from AI
Your SQL query is almost correct, but to get the maximum salary for each department along with the department name, it is better to group by the department ID and name to avoid issues with duplication or incorrect aggregation.
Correct query:
SELECT d.name, MAX(e.salary) AS max_salary
FROM Department d
LEFT JOIN Employee e ON e.dep_id = d.id
GROUP BY d.id, d.name
Explanation:
- We use LEFT JOIN to include departments without employees (in this case, max_salary will be NULL).
- We group by the unique department ID and name.
- The MAX(e.salary) function returns the highest salary in each department.
If you want to exclude departments without employees, you can use INNER JOIN instead of LEFT JOIN.