Introduction
Subqueries in the WHERE clause help you filter data by using the result of another query. This lets you find rows that match conditions based on other data.
Jump into concepts and practice - no test required
Subqueries in the WHERE clause help you filter data by using the result of another query. This lets you find rows that match conditions based on other data.
SELECT column1, column2 FROM table1 WHERE column3 operator (SELECT columnX FROM table2 WHERE condition);
SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders);
SELECT product_name FROM products WHERE category_id = (SELECT id FROM categories WHERE name = 'Beverages');
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 can return one or many values. Use IN for multiple values, = for a single value.
Make sure the subquery returns compatible data types for comparison.
Subqueries in WHERE let you filter rows based on another query's results.
Use IN when the subquery returns multiple values, = when it returns one.
This helps connect data from different tables easily.
WHERE clause do in SQL?WHERE clause to find employees in departments with ID 10 or 20?employees(emp_id, name, department_id)departments(department_id, name)SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE name = 'Sales');
SELECT * FROM orders WHERE customer_id = (SELECT customer_id FROM customers WHERE city = 'New York');
products(product_id, name)orders(order_id, product_id)