Subquery in FROM clause (derived table) in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use a subquery inside the FROM clause, it acts like a temporary table. We want to understand how the time to run this query grows as the data gets bigger.
How does the size of the original table affect the total work done?
Analyze the time complexity of the following code snippet.
SELECT dt.customer_id, dt.total_orders
FROM (
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
) AS dt
WHERE dt.total_orders > 5;
This query counts orders per customer in a subquery, then filters customers with more than 5 orders.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all rows in the orders table once to count orders per customer.
- How many times: Once over all orders (n rows), then grouping by customers.
As the number of orders grows, the database must look at each order once to count them.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 scans and counts |
| 100 | About 100 scans and counts |
| 1000 | About 1000 scans and counts |
Pattern observation: The work grows roughly in direct proportion to the number of orders.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of orders in the table.
[X] Wrong: "The subquery runs multiple times, so the time grows faster than the table size."
[OK] Correct: The subquery runs once to create the derived table, so the main cost is scanning the orders table once, not repeatedly.
Understanding how subqueries in the FROM clause affect performance helps you write efficient queries and explain your reasoning clearly in real-world situations.
"What if we added an index on customer_id in the orders table? How would the time complexity change?"
Practice
subquery in the FROM clause in SQL?Solution
Step 1: Understand the role of subqueries in FROM clause
Subqueries in the FROM clause act like temporary tables that the main query can use to simplify complex operations.Step 2: Differentiate from other SQL operations
Unlike DELETE or UPDATE, subqueries in FROM do not modify data but help organize data for selection.Final Answer:
To create a temporary table that can be used by the main query -> Option DQuick Check:
Subquery in FROM = temporary table [OK]
- Thinking subquery stores data permanently
- Confusing subquery with DELETE or UPDATE commands
- Forgetting subquery is temporary, not permanent
Solution
Step 1: Identify correct subquery syntax in FROM
The subquery must be enclosed in parentheses and given an alias using AS.Step 2: Check each option
SELECT * FROM (SELECT id FROM users) AS sub; correctly uses parentheses and alias. Others misuse WHERE, alias placement, or parentheses.Final Answer:
SELECT * FROM (SELECT id FROM users) AS sub; -> Option AQuick Check:
Subquery in FROM needs parentheses + alias [OK]
- Omitting alias for subquery
- Placing subquery in WHERE instead of FROM
- Incorrect alias placement
users(id, name)orders(id, user_id, amount)What will this query return?
SELECT sub.name, sub.total FROM (SELECT u.name, SUM(o.amount) AS total FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name) AS sub WHERE sub.total > 100;
Solution
Step 1: Understand the subquery
The subquery calculates total order amount per user by joining users and orders and grouping by user name.Step 2: Apply the outer WHERE filter
The outer query filters to only include users whose total order amount is greater than 100.Final Answer:
Names of users with total order amount greater than 100 -> Option AQuick Check:
Subquery sums orders; outer filters total > 100 [OK]
- Ignoring the WHERE filter on total
- Assuming all users are returned
- Confusing alias usage
SELECT sub.name, sub.total FROM (SELECT name, SUM(amount) AS total FROM users JOIN orders ON users.id = orders.user_id) sub;
Solution
Step 1: Analyze the subquery aggregation
The subquery uses SUM(amount) but does not group by name, which is required when selecting non-aggregated columns.Step 2: Confirm alias and JOIN syntax
The subquery has an alias 'sub' and JOIN syntax is correct, so these are not errors.Final Answer:
Missing GROUP BY clause in subquery -> Option CQuick Check:
Aggregation needs GROUP BY for non-aggregated columns [OK]
- Forgetting GROUP BY with aggregation
- Confusing alias requirement
- Misreading JOIN syntax
Solution
Step 1: Understand the requirement
We need average order amount per user but only for users with more than 3 orders.Step 2: Analyze each option
SELECT sub.user_id, sub.avg_amount FROM (SELECT user_id, AVG(amount) AS avg_amount FROM orders GROUP BY user_id HAVING COUNT(*) > 3) AS sub; correctly uses a subquery to group orders by user_id, filters users with more than 3 orders using HAVING, then calculates average amount.Final Answer:
SELECT sub.user_id, sub.avg_amount FROM (SELECT user_id, AVG(amount) AS avg_amount FROM orders GROUP BY user_id HAVING COUNT(*) > 3) AS sub; -> Option BQuick Check:
Subquery filters users by order count, outer selects average [OK]
- Using WHERE with aggregation functions
- Placing HAVING outside GROUP BY context
- Not using subquery to filter groups first
