Bird
Raised Fist0
MySQLquery~10 mins

Subqueries in FROM clause (derived tables) in MySQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Subqueries in FROM clause (derived tables)
Start Query
↓
Identify FROM clause
↓
Detect Subquery in FROM
↓
Execute Subquery
↓
Create Derived Table with Subquery Result
↓
Use Derived Table in Outer Query
↓
Execute Outer Query
↓
Return Final Result
The database first runs the subquery inside the FROM clause, treats its result as a temporary table, then runs the outer query using that temporary table.
Execution Sample
MySQL
SELECT dt.department, dt.avg_salary
FROM (SELECT department, AVG(salary) AS avg_salary
      FROM employees
      GROUP BY department) AS dt
WHERE dt.avg_salary > 50000;
This query calculates average salary per department using a subquery in FROM, then selects departments with average salary above 50000.
Execution Table
StepActionSubquery ResultDerived Table CreatedOuter Query FilterOutput Rows
1Start executing main queryN/AN/AN/AN/A
2Execute subquery in FROM clause[{department: 'HR', avg_salary: 48000}, {department: 'IT', avg_salary: 60000}, {department: 'Sales', avg_salary: 55000}]Derived table dt created with 3 rowsN/AN/A
3Apply WHERE filter on derived tableN/AN/Adt.avg_salary > 50000Rows with IT and Sales departments pass filter
4Return final resultN/AN/AN/A[{department: 'IT', avg_salary: 60000}, {department: 'Sales', avg_salary: 55000}]
5End query executionN/AN/AN/AFinal output returned
💡 All derived table rows processed; outer query filters applied; final rows returned.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
subquery_resultN/A[{department: 'HR', avg_salary: 48000}, {department: 'IT', avg_salary: 60000}, {department: 'Sales', avg_salary: 55000}]SameSame
derived_table_dtN/ACreated with 3 rowsSameSame
outer_query_outputN/AN/A[{department: 'IT', avg_salary: 60000}, {department: 'Sales', avg_salary: 55000}]Same
Key Moments - 3 Insights
Why does the subquery run before the outer query?
Because the subquery in the FROM clause creates a temporary table (derived table) that the outer query needs to use, so it must be executed first as shown in execution_table step 2.
Can we use column aliases from the subquery in the outer WHERE clause?
Yes, the outer query can use the aliases defined in the subquery because the subquery result is treated as a table with those columns, as seen in execution_table step 3 where dt.avg_salary is used.
What happens if the subquery returns no rows?
The derived table will be empty, so the outer query will have no rows to process and will return an empty result set, stopping execution after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the content of the derived table after step 2?
A[{department: 'HR', avg_salary: 60000}, {department: 'IT', avg_salary: 48000}]
B[{department: 'HR', avg_salary: 48000}, {department: 'IT', avg_salary: 60000}, {department: 'Sales', avg_salary: 55000}]
CEmpty table
DN/A
💡 Hint
Check the 'Subquery Result' and 'Derived Table Created' columns in execution_table row 2.
At which step does the outer query apply the WHERE filter?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Outer Query Filter' column in execution_table.
If the subquery returned no rows, what would be the output rows in the final result?
AEmpty result set
BAll rows from employees table
COnly rows with avg_salary > 50000
DError occurs
💡 Hint
Refer to key_moments explanation about empty subquery result and execution_table step 2.
Concept Snapshot
Subqueries in FROM clause create a temporary table called a derived table.
The subquery runs first, producing rows and columns.
The outer query treats this result as a table and can filter or join it.
Use alias for the subquery result to reference it in outer query.
This helps break complex queries into simpler parts.
Full Transcript
This visual execution trace shows how a subquery inside the FROM clause works in MySQL. First, the database runs the subquery to get a temporary table with department names and their average salaries. This temporary table is called a derived table and is given an alias 'dt'. Then, the outer query uses this derived table to select only those departments where the average salary is greater than 50000. The trace shows each step: starting the main query, executing the subquery, creating the derived table, applying the WHERE filter, and finally returning the filtered rows. Variables like the subquery result and derived table content are tracked step-by-step. Common confusions like why the subquery runs first and how aliases work are clarified. The quiz questions help reinforce understanding by asking about the derived table content, when filtering happens, and what if the subquery returns no rows.

Practice

(1/5)
1. What is the main purpose of using a subquery in the FROM clause in MySQL?
easy
A. To create a permanent table in the database
B. To update data in multiple tables at once
C. To delete rows based on a condition
D. To create a temporary table that the outer query can use

Solution

  1. Step 1: Understand the role of subqueries in FROM clause

    Subqueries in the FROM clause act like temporary tables that the outer query can use to simplify complex queries.
  2. Step 2: Differentiate from other SQL operations

    Updating or deleting data is not the purpose of subqueries in FROM; they are for organizing data selection.
  3. Final Answer:

    To create a temporary table that the outer query can use -> Option D
  4. Quick Check:

    Subquery in FROM = temporary table [OK]
Hint: Think of subquery in FROM as a temporary table [OK]
Common Mistakes:
  • Confusing subqueries in FROM with UPDATE or DELETE statements
  • Thinking subqueries create permanent tables
  • Ignoring the need for an alias for the subquery
2. Which of the following is the correct syntax for using a subquery in the FROM clause in MySQL?
easy
A. SELECT * FROM (SELECT id FROM users) AS sub;
B. SELECT * FROM users WHERE (SELECT id FROM users);
C. SELECT * FROM users (SELECT id FROM users);
D. SELECT * FROM users AS (SELECT id FROM users);

Solution

  1. Step 1: Identify correct subquery syntax in FROM clause

    The subquery must be enclosed in parentheses and given an alias using AS.
  2. Step 2: Check each option

    SELECT * FROM (SELECT id FROM users) AS sub; correctly uses parentheses and alias. Others misuse syntax or place subquery incorrectly.
  3. Final Answer:

    SELECT * FROM (SELECT id FROM users) AS sub; -> Option A
  4. Quick Check:

    Subquery in FROM needs parentheses + alias [OK]
Hint: Always alias your subquery in FROM clause [OK]
Common Mistakes:
  • Forgetting to alias the subquery
  • Placing subquery outside parentheses
  • Using subquery in WHERE or FROM incorrectly
3. Given the tables:
users(id, name)
orders(id, user_id, amount)
What will the following query return?
SELECT sub.user_id, sub.total_amount FROM (SELECT user_id, SUM(amount) AS total_amount FROM orders GROUP BY user_id) AS sub WHERE sub.total_amount > 100;
medium
A. List of all orders with amount greater than 100
B. List of user IDs with total order amount greater than 100
C. Syntax error due to missing alias
D. Empty result because no user has orders

Solution

  1. Step 1: Understand the subquery

    The subquery calculates total order amount per user by grouping orders by user_id and summing amounts.
  2. Step 2: Apply the outer query filter

    The outer query selects users whose total order amount is greater than 100 from the subquery result.
  3. Final Answer:

    List of user IDs with total order amount greater than 100 -> Option B
  4. Quick Check:

    Subquery sums orders; outer filters total_amount > 100 [OK]
Hint: Subquery groups and sums; outer filters results [OK]
Common Mistakes:
  • Confusing total order amount with individual order amounts
  • Forgetting to alias the subquery
  • Assuming syntax error without checking alias
4. Identify the error in the following query:
SELECT sub.user_id, sub.total FROM (SELECT user_id, SUM(amount) FROM orders GROUP BY user_id);
medium
A. GROUP BY cannot be used in subqueries
B. SUM(amount) must be renamed with AS
C. Missing alias for the subquery
D. SELECT cannot use subqueries in FROM clause

Solution

  1. Step 1: Check subquery alias requirement

    Subqueries in FROM clause must have an alias; this query lacks it.
  2. Step 2: Verify other parts

    SUM(amount) without alias is allowed but referencing it as sub.total will fail; aliasing subquery is mandatory.
  3. Final Answer:

    Missing alias for the subquery -> Option C
  4. Quick Check:

    Subquery in FROM needs alias [OK]
Hint: Always give an alias to subqueries in FROM [OK]
Common Mistakes:
  • Assuming SUM() must be aliased
  • Thinking GROUP BY is disallowed in subqueries
  • Ignoring alias requirement for subqueries
5. You want to find users who have placed orders totaling more than 500, but only include users who have more than 3 orders. Which query correctly uses a subquery in the FROM clause to achieve this?
Tables:
users(id, name)
orders(id, user_id, amount)
hard
A. SELECT u.name, stats.total_amount FROM users u JOIN (SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY user_id) AS stats ON u.id = stats.user_id WHERE stats.total_amount > 500 AND stats.order_count > 3;
B. SELECT u.name FROM users u WHERE (SELECT SUM(amount) FROM orders WHERE user_id = u.id) > 500 AND (SELECT COUNT(*) FROM orders WHERE user_id = u.id) > 3;
C. SELECT u.name, SUM(o.amount) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id HAVING SUM(o.amount) > 500 AND COUNT(o.id) > 3;
D. SELECT name FROM users WHERE id IN (SELECT user_id FROM orders GROUP BY user_id HAVING SUM(amount) > 500 AND COUNT(*) > 3);

Solution

  1. Step 1: Understand the requirement

    We need users with total order amount > 500 and more than 3 orders.
  2. Step 2: Analyze each option's approach

    SELECT u.name, stats.total_amount FROM users u JOIN (SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY user_id) AS stats ON u.id = stats.user_id WHERE stats.total_amount > 500 AND stats.order_count > 3; uses a subquery in FROM to calculate order count and total per user, then joins users to filter correctly. SELECT u.name FROM users u WHERE (SELECT SUM(amount) FROM orders WHERE user_id = u.id) > 500 AND (SELECT COUNT(*) FROM orders WHERE user_id = u.id) > 3; uses correlated subqueries but not FROM clause subquery. SELECT u.name, SUM(o.amount) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id HAVING SUM(o.amount) > 500 AND COUNT(o.id) > 3; uses HAVING but no subquery in FROM. SELECT name FROM users WHERE id IN (SELECT user_id FROM orders GROUP BY user_id HAVING SUM(amount) > 500 AND COUNT(*) > 3); uses IN with subquery but no join.
  3. Step 3: Confirm correct use of subquery in FROM

    Only SELECT u.name, stats.total_amount FROM users u JOIN (SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY user_id) AS stats ON u.id = stats.user_id WHERE stats.total_amount > 500 AND stats.order_count > 3; uses a derived table (subquery in FROM) with alias and joins properly.
  4. Final Answer:

    SELECT u.name, stats.total_amount FROM users u JOIN (SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY user_id) AS stats ON u.id = stats.user_id WHERE stats.total_amount > 500 AND stats.order_count > 3; -> Option A
  5. Quick Check:

    Subquery in FROM calculates stats; outer query filters users [OK]
Hint: Use subquery in FROM to pre-aggregate data, then join [OK]
Common Mistakes:
  • Not aliasing the subquery in FROM
  • Using correlated subqueries instead of derived tables
  • Missing join between users and subquery results
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard