Introduction
Subqueries help you get data step-by-step inside a bigger query. They let you ask a question inside another question.
Subqueries help you get data step-by-step inside a bigger query. They let you ask a question inside another question.
SELECT column1 FROM table WHERE column2 = (SELECT column2 FROM table2 WHERE condition);
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales');
SELECT product_name FROM products WHERE price > (SELECT AVG(price) FROM products);
SELECT customer_id, order_date FROM orders WHERE order_date = (SELECT MAX(order_date) FROM orders);
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'Marketing');
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'NY');(SELECT id FROM departments WHERE location = 'NY') finds department IDs located in NY.department_id matches any ID from the subquery result.SELECT * FROM table WHERE column = (SELECT MAX(column) FROM table); correctly uses parentheses and = with a subquery. The other options have syntax errors like using == instead of =, omitting parentheses entirely, or missing them after IN.SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
(SELECT AVG(salary) FROM employees) calculates the average salary of all employees.SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE name = 'Sales';
SELECT id FROM departments WHERE name = 'Sales', causing syntax error.Pass the test and this pattern moves unknown