Up until now, we have written "Flat" queries. Now we start nesting. A Subquery is simply a query inside another query. It is the SQL equivalent of a "callback function" or a "nested loop."
Subquery (Inner Query): A SELECT statement that is nested inside another statement (called the Outer Query). The inner query executes first and provides its result to the outer query.
Sometimes the data you need for a filter depends on another search.
- The Question: "Who earned more than the average salary?"
- The Problem: You don't know the average salary until you query it first.
- The Solution: A subquery calculates the
AVG(Salary), and the outer query uses that number to filter employees.
Subqueries can be placed in three main areas:
- WHERE Clause: Filter rows based on the result of another query.
- SELECT Clause: Generate a dynamic column value for every row.
- FROM Clause: Treat the result of a query as if it were a temporary table (Derived Table).
Generally, MySQL executes subqueries in a Bottom-Up fashion:
- The Inner Query runs once.
- Its result set (a value, a list, or a table) is stored in memory.
- The Outer Query runs, using that stored result to evaluate its conditions.
Note: For "Correlated Subqueries" (Topic 11.8), this changes to a Top-Down approach.
SELECT column_name
FROM table_name
WHERE column_name OPERATOR (SELECT column_name FROM table_name);
-- ^--- Subquery is always inside (Parentheses)"Find the most expensive product":
SELECT Product_Name, Price
FROM Products
WHERE Price = (SELECT MAX(Price) FROM Products);
-- The inner query finds (e.g.) 5000.
-- Then outer query becomes: WHERE Price = 5000.- Forgetting Parentheses: Subqueries must be wrapped in
(...). - Single-row vs. Multi-row mismatch:
If a subquery can return multiple rows, you must use
-- β ERROR if the subquery returns more than 1 row! WHERE Salary = (SELECT Salary FROM Employees WHERE Dept = 'Sales');
IN,ANY, orALLinstead of=.
Formatting for Readability: Always indent your subqueries. A flat query is easy to read, but nested queries become "Sphaghetti SQL" very quickly if not properly formatted.
SELECT Name
FROM Users
WHERE User_ID IN (
SELECT User_ID
FROM Logins
WHERE Login_Date = CURDATE()
);- Task 1: Write a query that finds all employees whose
Salaryis greater than the overallAVG(Salary)of the company. - Task 2: What is the difference between an "Inner Query" and an "Outer Query"?