MySQL Subquery
A subquery in MySQL is a query nested inside another query. Subqueries allow you to perform operations where the result of one query is used as input for another query.
Key Features
- Nesting: Subqueries can be nested within
SELECT
,FROM
, orWHERE
clauses. - Multiple Levels: Subqueries can be nested up to 64 levels.
- Return Types:
- A single value (scalar).
- A list of values.
- A table (used in the
FROM
clause).
Types of Subqueries
- Single-Row Subquery: Returns one row with one or more columns.
- Multi-Row Subquery: Returns multiple rows.
- Multi-Column Subquery: Returns multiple columns.
- Correlated Subquery: Refers to columns in the outer query.
Syntax
Subquery in SELECT
Subquery in WHERE
Subquery in FROM
Example Table
Table: employees
Table: departments
1. Subquery in the SELECT Clause
Find employees and the budget of their department:
Result
2. Subquery in the WHERE Clause
Find employees with a salary greater than the average salary:
Result
3. Subquery in the FROM Clause
List departments and their average employee salary:
Result
4. Correlated Subquery
Find employees who earn more than the average salary of their department:
Result
5. Multi-Row Subquery
Find departments where employees earn more than $5,000:
Result
6. Subquery with EXISTS
Check if the IT department has employees:
Result
Performance Tips
Indexing:
- Use indexes on columns involved in subqueries to improve performance.
Avoid Correlated Subqueries:
- Correlated subqueries are executed for each row in the outer query, which can be slow.
Replace with Joins:
- If possible, replace subqueries with
JOINs
for better performance.
- If possible, replace subqueries with
Use EXPLAIN:
- Analyze the query execution plan to identify inefficiencies.
Use Cases
- Filtering with Aggregates:
- E.g., employees earning above the average salary.
- Dynamic Conditions:
- E.g., matching values from other tables or calculations.
- Complex Reports:
- E.g., combining summarized and detailed data.
Let me know if you'd like to explore more examples or have questions!