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

MySQL subqueries

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:

idnameprice
1A100
2B200
3C300
4D400
5E500

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.

  1. MySQL Subquery Example:

    • Description: A subquery is a query nested within another query.
    • Example Code:
      SELECT column1, column2, ...
      FROM table_name
      WHERE column_name = (SELECT another_column FROM another_table WHERE condition);
      
  2. How to Use Subqueries in MySQL:

    • Description: Use subqueries to retrieve data that will be used by the main query.
    • Example Code:
      SELECT product_name
      FROM products
      WHERE category_id = (SELECT category_id FROM categories WHERE category_name = 'Electronics');
      
  3. Nested Queries in MySQL:

    • Description: Nest multiple subqueries within each other for more complex logic.
    • Example Code:
      SELECT *
      FROM products
      WHERE category_id IN (SELECT category_id FROM categories WHERE department_id = (SELECT department_id FROM departments WHERE department_name = 'Electronics'));
      
  4. Correlated Subqueries in MySQL:

    • Description: A correlated subquery refers to a subquery that depends on the outer query.
    • Example Code:
      SELECT product_name
      FROM products p
      WHERE price > (SELECT AVG(price) FROM products WHERE category_id = p.category_id);
      
  5. Scalar Subqueries in MySQL:

    • Description: Scalar subqueries return a single value and can be used in expressions.
    • Example Code:
      SELECT product_name, price,
             (SELECT AVG(price) FROM products) as avg_price
      FROM products;
      
  6. Subquery vs JOIN in MySQL:

    • Description: Subqueries and JOINs can achieve similar results. Subqueries are often used for simplicity, while JOINs can be more efficient.
    • Example Code (Subquery):
      SELECT product_name
      FROM products
      WHERE category_id = (SELECT category_id FROM categories WHERE category_name = 'Electronics');
      
    • Example Code (JOIN):
      SELECT product_name
      FROM products
      INNER JOIN categories ON products.category_id = categories.category_id
      WHERE categories.category_name = 'Electronics';
      
  7. Filtering with Subqueries in MySQL:

    • Description: Use subqueries in the WHERE clause for more dynamic filtering.
    • Example Code:
      SELECT order_id, order_date
      FROM orders
      WHERE customer_id IN (SELECT customer_id FROM customers WHERE country = 'USA');
      
  8. Using Subqueries in SELECT, WHERE, and FROM Clauses in MySQL:

    • Description: Subqueries can be used in various clauses for different purposes.
    • Example Code (SELECT):
      SELECT column1, (SELECT AVG(column2) FROM another_table) as avg_column2
      FROM table_name;
      
    • Example Code (WHERE):
      SELECT product_name
      FROM products
      WHERE price > (SELECT AVG(price) FROM products);
      
    • Example Code (FROM):
      SELECT department_name, (SELECT COUNT(*) FROM employees WHERE department_id = departments.department_id) as employee_count
      FROM departments;
      
  9. Examples of Complex Queries with MySQL Subqueries:

    • Description: Complex queries may involve multiple subqueries to achieve specific results.
    • Example Code:
      SELECT customer_id, customer_name
      FROM customers
      WHERE (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.customer_id) > 10;