You have 2 minutes to solve this SQL query.
Find employees who earn more than the average salary of their own department.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
employee_id,
employee_name,
department,
salary
FROM employees e
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE department = e.department
);
๐ก Explanation:
The query uses a correlated subquery to calculate the average salary for each employee's department.
โข The outer query iterates through each employee.
โข The inner query calculates the average salary of that employee's department.
โข If an employee's salary is greater than their department's average, they're included in the result.
This is a classic SQL interview question that tests your understanding of:
โ Correlated Subqueries
โ Aggregate Functions (AVG)
โ Filtering with WHERE
๐ฏ Expected Output Example
+----------+------------+--------+
| Employee | Department | Salary |
+----------+------------+--------+
| John | IT | 90,000 |
| Sarah | HR | 70,000 |
| David | Finance | 85,000 |
+----------+------------+--------+
(Only employees earning above their department's average salary.)
๐ Correlated subqueries are asked frequently in interviews. Learn when to use themโand also know how to rewrite them using window functions for better performance on large datasets.
โค๏ธ React with โค๏ธ for more SQL interview challenges!