w3resource

MySQL Aggregate Function Exercises: Find the manager ID and the salary of the lowest-paid employee for that manager

MySQL Aggregate Function: Exercise-9 with Solution

Write a query to find the manager ID and the salary of the lowest-paid employee for that manager.

Sample table: employees


Code:

-- Selecting the manager_id and the minimum salary for each manager
SELECT manager_id, MIN(salary) 
-- Selecting data from the employees table
FROM employees 
-- Filtering the result set to include only rows where manager_id is not NULL
WHERE manager_id IS NOT NULL 
-- Grouping the result set by manager_id
GROUP BY manager_id 
-- Sorting the result set by the minimum salary in descending order
ORDER BY MIN(salary) DESC;

Explanation:

  • This SQL query retrieves the manager_id and the minimum salary for each manager.
  • The WHERE clause filters the result set to include only rows where the manager_id is not NULL, ensuring that only employees with managers are considered.
  • The GROUP BY clause groups the result set by the manager_id, allowing for the calculation of the minimum salary for each manager.
  • The MIN() function calculates the minimum salary for each group of employees under the same manager.
  • The result set is sorted in descending order based on the minimum salary using the ORDER BY clause.
  • This query is useful when you want to find the minimum salary earned by each manager's direct reports and arrange them from the highest minimum salary to the lowest.

Relational Algebra Expression:

Relational Algebra Expression: Aggregate Function: Find the manager ID and the salary of the lowest-paid employee for that manager.

Relational Algebra Tree:

Relational Algebra Tree: Aggregate Function: Find the manager ID and the salary of the lowest-paid employee for that manager.

Pictorial Presentation of the above query

Pictorial: Query to find the manager ID and the salary of the lowest-paid employee for that manager

 

MySQL Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a query to get the difference between the highest and lowest salaries.
Next:Write a query to get the department ID and the total salary payable in each department.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.