Introduction
Subqueries with the IN operator help you find rows where a value matches any value from a list returned by another query.
Subqueries with the IN operator help you find rows where a value matches any value from a list returned by another query.
SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT column_name FROM another_table WHERE condition);
SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);
SELECT product_name FROM products WHERE category_id IN (SELECT id FROM categories WHERE name = 'Electronics');
SELECT employee_name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'New York');
This query finds employees who work in departments located in New York.
CREATE TABLE departments (id INT, name VARCHAR(20), location VARCHAR(20)); INSERT INTO departments VALUES (1, 'Sales', 'New York'), (2, 'HR', 'Chicago'), (3, 'IT', 'New York'); CREATE TABLE employees (id INT, employee_name VARCHAR(20), department_id INT); INSERT INTO employees VALUES (1, 'Alice', 1), (2, 'Bob', 2), (3, 'Charlie', 3), (4, 'Diana', 2); SELECT employee_name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'New York');
Subqueries with IN are useful for filtering based on related data.
Make sure the subquery returns only one column.
Using IN with a subquery can be slower on large data; indexes help improve speed.
Use IN with subqueries to match values from another table.
Subqueries return a list of values for the main query to check.
This helps connect related data easily without complex joins.
IN operator do when used with a subquery in MySQL?employees(id, name, department_id)departments(id, name)SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
SELECT * FROM orders WHERE customer_id IN SELECT id FROM customers WHERE city = 'New York';
products(id, name)orders(id, product_id, customer_id)customers(id, city)Pass the test and this pattern moves unknown