What if you could ask your database a tricky question in one simple step instead of many confusing ones?
Why subqueries are needed in PostgreSQL - The Real Reasons
Imagine you have a big list of customers and their orders in separate tables. You want to find customers who placed the largest order. Doing this by looking through each table manually or with many separate steps is like searching for a needle in a haystack by hand.
Manually combining data from multiple tables means writing long, complicated code or doing repetitive tasks. It's slow, easy to make mistakes, and hard to update if the data changes. You might miss important details or get wrong answers.
Subqueries let you write a small query inside another query. This means you can find the largest order first, then use that result immediately to find the matching customers. It keeps your work neat, fast, and less error-prone.
SELECT customer_id FROM orders; -- then separately find max order and matchSELECT customer_id FROM orders WHERE order_amount = (SELECT MAX(order_amount) FROM orders);
Subqueries let you solve complex questions in one clear step, making your data work smarter and faster.
A store manager wants to quickly find which customers spent the most money last month without flipping between many reports or spreadsheets.
Manual data checks are slow and error-prone.
Subqueries let you nest queries to handle complex data easily.
This makes your database work clearer, faster, and more reliable.
Practice
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = 'NY');Solution
Step 1: Understand the role of the subquery
The subquery(SELECT id FROM departments WHERE location = 'NY')finds department IDs located in NY.Step 2: See how the main query uses the subquery
The main query selects employees whosedepartment_idmatches any ID from the subquery result.Final Answer:
To ask a question inside another query and filter results based on it -> Option CQuick Check:
Subqueries filter data using inner query results [OK]
- Thinking subqueries speed up queries automatically
- Confusing subqueries with table creation
- Using subqueries to change data types
Solution
Step 1: Identify correct subquery syntax
Subqueries must be enclosed in parentheses and used with comparison operators like = or IN.Step 2: Check each option
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.Final Answer:
SELECT * FROM table WHERE column = (SELECT MAX(column) FROM table); -> Option BQuick Check:
Subqueries need parentheses and proper operators [OK]
- Using double equals (==) instead of single equals (=)
- Omitting parentheses around subqueries
- Using IN without parentheses
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
Solution
Step 1: Understand the subquery
The subquery(SELECT AVG(salary) FROM employees)calculates the average salary of all employees.Step 2: Apply the condition in the main query
The main query selects employee names where their salary is greater than this average.Final Answer:
Names of employees earning more than the average salary -> Option DQuick Check:
Subquery returns average; main query filters salaries above it [OK]
- Thinking it returns employees below average
- Assuming syntax error due to subquery
- Confusing AVG with SUM
SELECT name FROM employees WHERE department_id = SELECT id FROM departments WHERE name = 'Sales';
Solution
Step 1: Check subquery syntax
The subquery must be enclosed in parentheses to be valid in the WHERE clause.Step 2: Identify the missing parentheses
The query misses parentheses aroundSELECT id FROM departments WHERE name = 'Sales', causing syntax error.Final Answer:
Missing parentheses around the subquery -> Option AQuick Check:
Subqueries need parentheses to be valid [OK]
- Forgetting parentheses around subqueries
- Assuming wrong operator causes error
- Thinking table name is incorrect
Solution
Step 1: Understand the requirement
We need to compare each employee's salary to the average salary of their own department.Step 2: Analyze each option
SELECT name, salary, department_id FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = employees.department_id); uses a correlated subquery that calculates average salary per employee's department. SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees); compares to overall average, ignoring departments. SELECT name FROM employees WHERE salary > ALL (SELECT salary FROM employees); compares salary to all salaries, not averages. SELECT name FROM employees WHERE salary > ANY (SELECT AVG(salary) FROM employees GROUP BY department_id); compares to a list of averages but uses ANY incorrectly.Final Answer:
SELECT name, salary, department_id FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = employees.department_id); -> Option AQuick Check:
Correlated subquery compares salary to department average [OK]
- Comparing to overall average instead of department average
- Using ALL or ANY incorrectly with averages
- Not correlating subquery with outer query
Ready to prove it?
Pass the test and this pattern moves unknown
