MySQL Subqueries Examples
Quick Answer
MySQL subqueries are nested queries used within another SQL statement to perform complex data retrieval. They can appear in SELECT, WHERE, or FROM clauses and help filter, compare, or aggregate data dynamically. Using subqueries improves query flexibility and readability.
Learning Objectives
- Understand what subqueries are and where they can be used in MySQL.
- Write subqueries in SELECT, WHERE, and FROM clauses with practical examples.
- Learn how subqueries can simplify complex queries and improve readability.
Introduction
Subqueries are a powerful feature in MySQL that let you nest one query inside another.
They help you perform complex data retrieval tasks by breaking down queries into manageable parts.
Think of subqueries as queries within queries, enabling dynamic and flexible data selection.
What is a Subquery?
A subquery is a SQL query nested inside another query. It returns data that the outer query can use.
Subqueries can return a single value, a list of values, or a table of results depending on context.
- Used to filter results dynamically.
- Can be placed in SELECT, WHERE, or FROM clauses.
- Helps avoid complex joins in some cases.
Subquery in WHERE Clause
One common use of subqueries is in the WHERE clause to filter rows based on related data.
This allows you to compare a column against the result of another query.
- Returns rows where a condition matches the subquery result.
- Can use operators like IN, EXISTS, or comparison operators.
Example: Find Employees in Departments with More Than 5 Employees
This query uses a subquery in the WHERE clause to filter employees based on department size.
Subquery in SELECT Clause
Subqueries can be used in the SELECT clause to compute values for each row dynamically.
This is useful for adding calculated columns based on related data.
- Returns a scalar value for each row processed by the outer query.
- Can be used to fetch related data without joins.
Example: Show Employee Name with Their Department Name
This example uses a subquery in SELECT to fetch the department name for each employee.
Subquery in FROM Clause
Subqueries can also appear in the FROM clause, acting as temporary tables for the outer query.
This technique is useful for breaking complex queries into simpler parts.
- The subquery result is treated like a table or view.
- Allows aggregation or filtering before joining or selecting.
Example: Average Salary per Department Using Subquery in FROM
This query calculates average salaries per department using a subquery in the FROM clause.
Practical Example
This query selects employees who work in departments with more than 5 employees.
This query lists employees along with their department names using a subquery in the SELECT clause.
This query calculates the average salary per department by using a subquery in the FROM clause.
Examples
SELECT employee_name FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE employee_count > 5);This query selects employees who work in departments with more than 5 employees.
SELECT employee_name, (SELECT department_name FROM departments WHERE departments.department_id = employees.department_id) AS dept_name FROM employees;This query lists employees along with their department names using a subquery in the SELECT clause.
SELECT dept_id, AVG(salary) AS avg_salary FROM (SELECT department_id AS dept_id, salary FROM employees) AS dept_salaries GROUP BY dept_id;This query calculates the average salary per department by using a subquery in the FROM clause.
Best Practices
- Use subqueries to simplify complex queries but avoid over-nesting which can hurt performance.
- Prefer JOINs when retrieving related data from multiple tables for better readability and optimization.
- Use EXISTS instead of IN for subqueries that check for existence to improve performance.
- Test subqueries independently to ensure they return expected results before embedding.
Common Mistakes
- Using subqueries that return multiple columns where only one is expected.
- Writing subqueries that return multiple rows when a single value is required.
- Overusing subqueries instead of more efficient JOINs.
- Ignoring performance implications of nested subqueries on large datasets.
Hands-on Exercise
Write a Subquery in WHERE Clause
Write a query to find all products priced higher than the average price of all products.
Expected output: List of products with price greater than average price.
Hint: Use a subquery in the WHERE clause to calculate the average price.
Use Subquery in SELECT Clause
Write a query to list customers with the total number of orders they have placed using a subquery in SELECT.
Expected output: Customer names with their order counts.
Hint: Use a subquery to count orders per customer.
Subquery in FROM Clause Practice
Write a query to find departments with average employee salary above 50000 using a subquery in FROM.
Expected output: Departments where average salary exceeds 50000.
Hint: Calculate average salary per department in the subquery.
Interview Questions
What is a subquery in MySQL?
InterviewA subquery is a query nested inside another SQL query that provides data to the outer query.
Where can subqueries be used in a MySQL statement?
InterviewSubqueries can be used in SELECT, WHERE, and FROM clauses.
When should you prefer JOINs over subqueries?
InterviewJOINs are preferred when retrieving related data from multiple tables for better performance and readability.
MCQ Quiz
1. What is the best first step when learning Examples?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Examples?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. MySQL subqueries are nested queries used within another SQL statement to perform complex data retrieval.
B. Examples never needs examples
C. Examples is unrelated to practical work
D. Examples should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Subqueries allow embedding one query inside another to perform dynamic filtering or aggregation.
- They can be used in SELECT, WHERE, and FROM clauses depending on the use case.
- Proper use of subqueries can simplify complex SQL logic and improve maintainability.
- MySQL subqueries are nested queries used within another SQL statement to perform complex data retrieval.
- They can appear in SELECT, WHERE, or FROM clauses and help filter, compare, or aggregate data dynamically.
Summary
MySQL subqueries are nested queries that enable dynamic and flexible data retrieval.
They can be used in WHERE, SELECT, and FROM clauses to filter, calculate, or transform data.
Understanding how and when to use subqueries helps write clearer and more maintainable SQL queries.
Frequently Asked Questions
Can subqueries return multiple rows?
Yes, subqueries can return multiple rows, especially when used with IN or EXISTS operators.
Are subqueries always better than JOINs?
No, JOINs are often more efficient and readable for combining related tables, while subqueries are better for filtering or calculating.
What is the difference between correlated and non-correlated subqueries?
A correlated subquery depends on the outer query for its values, while a non-correlated subquery runs independently.





