A subquery is a query inside another SQL query. It can be used in SELECT, FROM, or WHERE clauses to make your main query more powerful and dynamic.
Get employees who earn more than the average salary:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
π Shows employees earning more than the companyβs average salary.
Find the highest paid employee in each department:
SELECT dept_id, MAX(salary) AS max_salary
FROM (SELECT dept_id, salary FROM employees) AS temp
GROUP BY dept_id;
π The inner query creates a temporary table used by the outer query.
Show employee name and their department name without using JOIN:
SELECT name,
(SELECT department_name
FROM departments d
WHERE d.id = e.dept_id) AS dept_name
FROM employees e;
A correlated subquery depends on the outer query for its values.
SELECT name, salary
FROM employees e
WHERE salary > (SELECT AVG(salary)
FROM employees
WHERE dept_id = e.dept_id);
π Compares each employeeβs salary with the average salary of their department.
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM departments d WHERE d.id = e.dept_id);
π Returns employees only if their department exists in the departments table.
=, <, >).IN, ANY, ALL).