Q22. Employees earning above the company average
List employees who earn more than the average salary of all employees (83250).
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;
-- Arjun 150000, Omkar 130000, Gauri 120000, Bhavna 110000,
-- Chirag 95000, Tara 95000, Deepa 90000, Lakshmi 90000,
-- Esha 85000, Farhan 85000 (10 rows)Q23. Customers who bought a Laptop (IN)
Find customers who have ordered the product 'Laptop'.
SELECT name
FROM customers
WHERE customer_id IN (
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE p.name = 'Laptop'
)
ORDER BY name;
-- Aman
-- GopalQ24. Customers with a cancelled order (EXISTS)
Find customers who have at least one cancelled order.
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.status = 'Cancelled'
)
ORDER BY c.name;
-- Divya
-- HeenaQ25. Products that were never ordered (NOT EXISTS)
Find products that do not appear in any order.
SELECT p.product_id, p.name
FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id
);
-- product_id | name
-- 10 | SunglassesQ26. Employees earning above their department average (correlated)
List employees who earn more than the average salary of their own department. Employees with no department drop out automatically.
SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(salary)
FROM employees
WHERE dept_id = e.dept_id
)
ORDER BY e.dept_id, e.salary DESC;
-- name | dept_id | salary
-- Arjun | 1 | 150000
-- Bhavna | 1 | 110000
-- Gauri | 2 | 120000
-- Harsh | 2 | 80000
-- Lakshmi | 3 | 90000
-- Omkar | 4 | 130000Q27. Second highest salary
Find the second highest distinct salary in the company.
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- second_highest
-- 130000