SQL Assignment and Queries with Outputs
I. Find employees working in the same department as 'Alice'.
SELECT emp_name
FROM Employees
WHERE dept_id = (SELECT dept_id FROM Employees WHERE emp_name = 'Alice');
Expected Output:
Alice, Emma
II. List employees who earn more than the average salary.
SELECT emp_name
FROM Employees
WHERE salary > (SELECT AVG(salary) FROM Employees);
Expected Output:
Emma, Charlie
III. Find employees whose department name contains 'IT'.
SELECT emp_name
FROM Employees E
JOIN Departments D ON E.dept_id = D.dept_id
WHERE D.dept_name LIKE '%IT%';
Expected Output:
Bob, Frank
IV. Find the highest-paid employee in each department.
SELECT emp_name, dept_id, salary
FROM (
SELECT emp_name, dept_id, salary,
RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rank
FROM Employees
)
WHERE rank = 1;
Expected Output:
Emma (HR), Charlie (Finance), Bob (IT)
V. Find departments with no employees.
SELECT dept_name
FROM Departments
WHERE dept_id NOT IN (SELECT DISTINCT dept_id FROM Employees);
Expected Output:
Marketing
VI. Retrieve employees earning less than the average salary in their
department.
SELECT emp_name
FROM Employees E
WHERE salary < (
SELECT AVG(salary)
FROM Employees
WHERE dept_id = E.dept_id
);
Expected Output:
Alice, Frank
VII. Find employees whose salary is the second highest.
SELECT emp_name, salary
FROM (
SELECT emp_name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
FROM Employees
)
WHERE rank = 2;
Expected Output:
Bob
VIII. Find departments where the total salary of employees exceeds 10,000.
SELECT D.dept_name
FROM Departments D
JOIN Employees E ON D.dept_id = E.dept_id
GROUP BY D.dept_name
HAVING SUM(E.salary) > 10000;
Expected Output:
HR, IT
IX. Find employees who earn more than the highest-paid employee in the 'IT'
department.
SELECT emp_name
FROM Employees
WHERE salary > (
SELECT MAX(salary)
FROM Employees
WHERE dept_id = '20' -- IT department
);
Expected Output:
Emma
X. Find employees who do not earn the minimum or maximum salary in their
department.
SELECT emp_name
FROM Employees E
WHERE salary > (
SELECT MIN(salary)
FROM Employees
WHERE dept_id = E.dept_id
)
AND salary < (
SELECT MAX(salary)
FROM Employees
WHERE dept_id = E.dept_id
);
Expected Output:
Alice, Frank, Charlie