MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
A subquery, also known as a nested query or inner query, is a query that's embedded within the main SQL query. It can be used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with SELECT
, INSERT
, UPDATE
, and DELETE
statements along with operators like =
, <
, >
, >=
, <=
, IN
, BETWEEN
etc.
Basic Usage of a Subquery
Consider a products
table:
id | name | price |
---|---|---|
1 | A | 100 |
2 | B | 200 |
3 | C | 300 |
4 | D | 400 |
5 | E | 500 |
And you want to find products that have a price less than the average price. You can use a subquery to find the average price and use that in your main query. Here's how:
SELECT name, price FROM products WHERE price < (SELECT AVG(price) FROM products);
The subquery (SELECT AVG(price) FROM products)
calculates the average price of all products. The main query then retrieves the products that have a price less than this average price.
Subquery in the FROM Clause
A subquery can also be used in the FROM
clause. This is useful when you need to perform an operation on the result set of a query. For example, to find the average price of products that cost more than 200:
SELECT AVG(price) FROM (SELECT price FROM products WHERE price > 200) AS expensive_products;
Here, the subquery (SELECT price FROM products WHERE price > 200)
retrieves the prices of products that cost more than 200. This result set is then treated as a table named expensive_products
from which the main query selects the average price.
Subquery in the SELECT Clause
A subquery can also be used in the SELECT
clause. This is useful when you want to include additional data in the result set that's based on a calculation or aggregation. For instance, to include the average price alongside product information:
SELECT name, price, (SELECT AVG(price) FROM products) AS average_price FROM products;
Here, the subquery (SELECT AVG(price) FROM products)
calculates the average price of all products. The main query then retrieves the name, price, and the average price for each product.
Subquery with the IN Operator
You can also use a subquery with the IN
operator. For example, if you have another table, orders
, and you want to find products that have been ordered, you could use:
SELECT name FROM products WHERE id IN (SELECT product_id FROM orders);
Here, the subquery (SELECT product_id FROM orders)
retrieves the ids of all products that have been ordered. The main query then retrieves the names of products that have been ordered.
Please note that subqueries can be slow, especially on large tables, because the inner query is executed for each row in the outer query. When performance is a concern, it's often possible to rewrite subqueries as joins or other constructs.
MySQL Subquery Example:
SELECT column1, column2, ... FROM table_name WHERE column_name = (SELECT another_column FROM another_table WHERE condition);
How to Use Subqueries in MySQL:
SELECT product_name FROM products WHERE category_id = (SELECT category_id FROM categories WHERE category_name = 'Electronics');
Nested Queries in MySQL:
SELECT * FROM products WHERE category_id IN (SELECT category_id FROM categories WHERE department_id = (SELECT department_id FROM departments WHERE department_name = 'Electronics'));
Correlated Subqueries in MySQL:
SELECT product_name FROM products p WHERE price > (SELECT AVG(price) FROM products WHERE category_id = p.category_id);
Scalar Subqueries in MySQL:
SELECT product_name, price, (SELECT AVG(price) FROM products) as avg_price FROM products;
Subquery vs JOIN in MySQL:
SELECT product_name FROM products WHERE category_id = (SELECT category_id FROM categories WHERE category_name = 'Electronics');
SELECT product_name FROM products INNER JOIN categories ON products.category_id = categories.category_id WHERE categories.category_name = 'Electronics';
Filtering with Subqueries in MySQL:
SELECT order_id, order_date FROM orders WHERE customer_id IN (SELECT customer_id FROM customers WHERE country = 'USA');
Using Subqueries in SELECT, WHERE, and FROM Clauses in MySQL:
SELECT column1, (SELECT AVG(column2) FROM another_table) as avg_column2 FROM table_name;
SELECT product_name FROM products WHERE price > (SELECT AVG(price) FROM products);
SELECT department_name, (SELECT COUNT(*) FROM employees WHERE department_id = departments.department_id) as employee_count FROM departments;
Examples of Complex Queries with MySQL Subqueries:
SELECT customer_id, customer_name FROM customers WHERE (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.customer_id) > 10;