What are Subqueries?

Subqueries, also known as inner queries or nested queries, are a powerful feature of SQL that allows you to nest one query within another. They are used to retrieve data from one or more tables and use that result in another query. Subqueries enable you to perform more complex operations and retrieve specific information from your database.


Basic Syntax of Subqueries

The basic syntax of a subquery is as follows:

            SELECT column1
FROM table1
WHERE column2 operator (SELECT column3 FROM table2 WHERE condition);

In this syntax:

  • column1
    is the column you want to retrieve.
  • table1
    is the table from which you want to retrieve data.
  • column2
    is the column used to filter the results.
  • operator
    is a comparison operator (e.g.,
    =
    ,
    <
    ,
    >
    ).
  • column3
    is the column you're comparing with in the subquery.
  • table2
    is the table used in the subquery.
  • condition
    is the condition used in the subquery to filter data.

Example: Using Subqueries for Data Retrieval

Let's say you have two tables: "orders" and "customers," and you want to retrieve the names of customers who have placed orders. You can use a subquery to achieve this:

            SELECT customer_name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);

This query retrieves customer names from the "customers" table where the

customer_id
exists in the result of the subquery, which selects
customer_id
from the "orders" table.


Conclusion

SQL subqueries in MySQL are a valuable tool for performing complex queries and data retrieval operations. You've learned the basic syntax of subqueries and how to use them in a simple example. As you advance in your SQL knowledge, subqueries will enable you to tackle more intricate data manipulation tasks and make your queries more efficient and precise.