Subqueries in WHERE with IN in PostgreSQL - Time & Space Complexity
When using a subquery inside a WHERE clause with IN, the database checks if values match a list from another query.
We want to know how the time to run this query changes as the size of the data grows.
Analyze the time complexity of the following code snippet.
SELECT employee_id, name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location = 'New York'
);
This query finds employees who work in departments located in New York.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: For each employee, check if their department_id is in the list returned by the subquery.
- How many times: This check happens once for every employee row.
As the number of employees grows, the database must check more rows against the subquery result.
| Input Size (n employees) | Approx. Operations |
|---|---|
| 10 | About 10 checks against the subquery list |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to the number of employees.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of employees.
[X] Wrong: "The subquery runs once and does not affect the total time much."
[OK] Correct: The subquery result is used for every employee check, so its size and how the database handles it impact the total time.
Understanding how subqueries affect query time helps you write efficient database queries and explain your reasoning clearly in interviews.
"What if we replaced IN with EXISTS? How would the time complexity change?"
Practice
IN keyword do in a SQL query when used with a subquery in the WHERE clause?Solution
Step 1: Understand the role of
TheINwith subqueriesINkeyword checks if a value exists in a list of values returned by the subquery.Step 2: Identify the filtering effect
Rows are kept only if their column value matches any value from the subquery's result.Final Answer:
It filters rows where a column's value matches any value returned by the subquery. -> Option AQuick Check:
INfilters rows by subquery values [OK]
- Confusing IN with JOIN
- Thinking IN updates or deletes rows
- Assuming IN returns a single value only
IN in PostgreSQL?Solution
Step 1: Check the correct use of parentheses
The subquery must be enclosed in parentheses afterIN.Step 2: Verify the subquery returns a single column
The subquery should return one column of values to compare against.Final Answer:
SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments); -> Option BQuick Check:
Subquery in parentheses with single column [OK]
- Using = IN instead of just IN
- Omitting parentheses around subquery
- Selecting multiple columns in subquery
employees(id, name, department_id)departments(id, name)What will this query return?
SELECT name FROM employees WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
Solution
Step 1: Understand the subquery filtering departments
The subquery selects department IDs where the department name is 'Sales'.Step 2: Filter employees by matching department IDs
The main query returns employee names whose department_id matches those IDs.Final Answer:
Names of employees who work in the Sales department. -> Option DQuick Check:
IN filters employees by Sales department IDs [OK]
- Thinking it returns all employees
- Confusing NOT IN with IN
- Assuming subquery causes error with multiple rows
SELECT * FROM employees WHERE department_id IN SELECT id FROM departments WHERE name = 'HR';
Solution
Step 1: Check syntax for subquery with IN
The subquery must be enclosed in parentheses after the IN keyword.Step 2: Identify missing parentheses causing syntax error
The query lacks parentheses around the subquery, causing invalid syntax.Final Answer:
Missing parentheses around the subquery after IN. -> Option AQuick Check:
Subquery must be in parentheses after IN [OK]
- Omitting parentheses around subquery
- Confusing IN with EXISTS syntax
- Assuming subquery returns multiple columns
customers(id, name)orders(id, customer_id, product_id)products(id, name, category)Which query correctly uses a subquery with
IN to get these customers?Solution
Step 1: Identify the correct subquery for products in 'Electronics'
The innermost subquery selects product IDs where category is 'Electronics'.Step 2: Use these product IDs to find matching orders
The middle subquery selects customer IDs from orders with those product IDs.Step 3: Select customer names whose IDs match those customer IDs
The main query selects customer names where their ID is in the list from the orders subquery.Final Answer:
SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders WHERE product_id IN (SELECT id FROM products WHERE category = 'Electronics')); -> Option CQuick Check:
Nested IN subqueries filter customers by product category [OK]
- Using = IN instead of IN
- Mixing up customer_id and product_id columns
- Selecting wrong columns in subqueries
Ready to prove it?
Pass the test and this pattern moves unknown
