A subquery (or inner query) is a query nested inside another SQL query.
Subqueries can be used in SELECT
, FROM
, WHERE
, or HAVING
clauses to break complex tasks into simpler parts.
Find employees earning more than the average salary:
SELECT first_name, last_name, salary FROM employees WHERE salary > ( SELECT AVG(salary) FROM employees );
Use a subquery as a derived table to get department averages, then filter:
SELECT dept, avg_salary FROM ( SELECT department AS dept, AVG(salary) AS avg_salary FROM employees GROUP BY department ) AS dept_avg WHERE avg_salary > 60000;
For each employee, show those whose salary is above their department’s average:
SELECT e.first_name, e.last_name, e.department, e.salary FROM employees AS e WHERE e.salary > ( SELECT AVG(salary) FROM employees WHERE department = e.department );
Include a count of orders per customer in the result:
SELECT c.customer_name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count FROM customers AS c;
JOIN
s or WITH
(CTEs) for complex operations in MySQL 8.0+.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!