Introduction
Subqueries let you put one query inside another. This helps you get data step-by-step, like solving a puzzle piece by piece.
Subqueries let you put one query inside another. This helps you get data step-by-step, like solving a puzzle piece by piece.
SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT column3 FROM table2 WHERE condition );
SELECT name FROM employees WHERE department_id IN ( SELECT id FROM departments WHERE location = 'New York' );
SELECT product_name FROM products WHERE price > ( SELECT AVG(price) FROM products );
This example creates two tables, fills them with data, and then finds employees working in New York departments using a subquery.
CREATE TABLE departments ( id INT PRIMARY KEY, name VARCHAR(50), location VARCHAR(50) ); CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50), department_id INT ); INSERT INTO departments VALUES (1, 'Sales', 'New York'), (2, 'HR', 'Chicago'), (3, 'IT', 'New York'); INSERT INTO employees VALUES (1, 'Alice', 1), (2, 'Bob', 2), (3, 'Charlie', 3), (4, 'Diana', 1); SELECT name FROM employees WHERE department_id IN ( SELECT id FROM departments WHERE location = 'New York' );
Subqueries can return one or many rows depending on how they are used.
Using subqueries can make complex filtering easier to understand.
Subqueries let you nest one query inside another to use its results.
They help break down complex questions into smaller steps.
Subqueries are useful for filtering, comparing, and calculating data based on other data.
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'NY');SELECT id FROM departments WHERE location = 'NY' finds department IDs in New York.department_id matches those IDs from the subquery.SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'LA');
SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE location = 'NY';
SELECT id FROM departments WHERE location = 'NY'.Pass the test and this pattern moves unknown