How to Use the IN Operator with a SubQuery in SQL?


The IN operator in SQL is used to check whether a value matches any value in a list or a subquery. When used with a subquery, the IN operator compares the result set of the subquery with the values in the main query.

Here's an example of how to use the IN operator with a subquery in SQL:

Suppose we have two tables, "customers" and "orders". The "customers" table has columns "customer_id" and "customer_name", while the "orders" table has columns "order_id", "customer_id", and "order_date".

We want to find all the customers who have placed an order in the month of January. We can use the IN operator with a subquery to achieve this:

SELECT customer_name
FROM customers
WHERE customer_id IN (
  SELECT customer_id
  FROM orders
  WHERE MONTH(order_date) = 1
);

In this example, the subquery selects all the customer IDs from the "orders" table where the order date is in January. The main query then selects the customer names from the "customers" table where the customer ID matches any of the IDs returned by the subquery.

Another way to achieve the same result is by using a JOIN instead of a subquery:

SELECT customer_name
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
WHERE MONTH(order_date) = 1;

In this example, the JOIN combines the "customers" and "orders" tables based on the customer ID column. The WHERE clause filters the result set to only include orders placed in January. Finally, the SELECT statement returns the customer names from the "customers" table.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.