๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ: You have 2 minutes to solve this SQL queryโ€ฆ

๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ:
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!
โค9๐Ÿ”ฅ5
November 23, 2026 1.4K 2