Subqueries let you run a query inside another query. This helps you filter or calculate data first, then use that result in the main query. It makes complex data retrieval easier and clearer.
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
employees: 1, 'Alice', 2 2, 'Bob', 3 3, 'Charlie', 2 4, 'Diana', 1 departments: 1, 'HR' 2, 'Sales' 3, 'Marketing'
The subquery finds the id of the 'Sales' department, which is 2. The main query selects employees whose department_id is 2. That includes Alice and Charlie.
SELECT * FROM orders WHERE customer_id = (SELECT id FROM customers WHERE name = 'John');
Option D is missing parentheses around the subquery after IN, which causes a syntax error. The correct syntax requires parentheses enclosing the subquery.
Subqueries are useful when you want to filter rows based on aggregated data, such as maximum values or counts, which can be complex to do with JOINs alone.
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE location = 'New York');
Assume the subquery returns multiple department ids.
The '=' operator expects a single value on the right side. If the subquery returns multiple rows, PostgreSQL raises an error about multiple rows returned.