๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find employees whose salary is higher than the average salary of all other departments (excluding their own department).
Assume the table structure:
employees(employee_id, employee_name, department, salary)
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
employee_id,
employee_name,
department,
salary
FROM employees e1
WHERE salary > (
SELECT AVG(salary)
FROM employees e2
WHERE e2.department <> e1.department
);
๐ก Explanation:
This query compares each employee's salary against the average salary of all employees outside their own department.
โข The outer query processes each employee.
โข The correlated subquery calculates the average salary of employees in all other departments.
โข Employees whose salary exceeds that average are returned.
This question tests your understanding of:
โ
Correlated Subqueries
โ
Aggregate Functions (AVG)
โ
Conditional Filtering
โ
Cross-group Comparisons
๐ฏ Expected Output Example
Employee: John | Department: IT | Salary: 95,000
Employee: Sarah | Department: HR | Salary: 82,000
๐ Alternative Using Common Table Expressions (CTEs)
WITH dept_avg AS (
SELECT
department,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department
)
SELECT
e.employee_id,
e.employee_name,
e.department,
e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(avg_salary)
FROM dept_avg d
WHERE d.department <> e.department
);
This version first computes department-level averages and then compares each employee's salary with the average of the other departments' averages.
๐ Tip for SQL Job Seekers:
Interviewers often ask questions that compare data within a group versus outside a group. These problems test your understanding of correlated subqueries and aggregate calculations across multiple levels.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2939
4.07K
- โค 11