0
0
PostgreSQLquery~10 mins

Subqueries in FROM (derived tables) in PostgreSQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Subqueries in FROM (derived tables)
Start Query
Execute Subquery in FROM
Create Derived Table with Subquery Result
Use Derived Table in Outer Query
Apply Outer Query Conditions/Aggregations
Return Final Result
The query first runs the subquery inside FROM, creating a temporary table (derived table). Then the outer query uses this derived table to produce the final result.
Execution Sample
PostgreSQL
SELECT dt.department, AVG(dt.salary) AS avg_salary
FROM (SELECT department, salary FROM employees) AS dt
GROUP BY dt.department;
This query calculates the average salary per department by first selecting department and salary from employees as a derived table.
Execution Table
StepActionSubquery ResultDerived Table CreatedOuter Query OperationOutput
1Execute subquery SELECT department, salary FROM employees[{Sales, 5000}, {Sales, 6000}, {HR, 4500}, {HR, 4700}]Derived table dt with 4 rowsN/AN/A
2Use derived table dt in outer queryN/Adt availableGroup rows by departmentN/A
3Calculate AVG(salary) for SalesN/Adt availableAVG(5000,6000) = 5500Sales, 5500
4Calculate AVG(salary) for HRN/Adt availableAVG(4500,4700) = 4600HR, 4600
5Return final resultN/AN/AN/A[{Sales, 5500}, {HR, 4600}]
💡 All rows processed and grouped, final averages computed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
subquery_resultempty[{Sales,5000},{Sales,6000},{HR,4500},{HR,4700}][{Sales,5000},{Sales,6000},{HR,4500},{HR,4700}][{Sales,5000},{Sales,6000},{HR,4500},{HR,4700}][{Sales,5000},{Sales,6000},{HR,4500},{HR,4700}][{Sales,5000},{Sales,6000},{HR,4500},{HR,4700}]
derived_table_dtnonecreated with 4 rowsavailable for groupingavailable for groupingavailable for groupingavailable for grouping
avg_salary_Salesnonenonenone550055005500
avg_salary_HRnonenonenonenone46004600
Key Moments - 3 Insights
Why do we need to give the subquery an alias like 'dt'?
The alias 'dt' names the derived table so the outer query can refer to it. Without it, the query will cause an error. See execution_table step 2 where 'dt' is used.
Is the subquery executed before or after the outer query?
The subquery runs first to produce the derived table. Then the outer query uses that result. This is shown in execution_table steps 1 and 2.
Can the outer query use columns directly from the original table?
No, when using a subquery in FROM, the outer query only sees the columns output by the subquery (derived table). It cannot access original tables directly here.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the average salary for the Sales department at step 3?
A6000
B5500
C5000
D4600
💡 Hint
Check the 'Outer Query Operation' and 'Output' columns at step 3 in the execution_table.
At which step is the derived table 'dt' created and ready for use?
AStep 1
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Derived Table Created' column in the execution_table to find when 'dt' is created.
If the subquery selected an extra column 'employee_id', how would the outer query be affected?
AThe outer query cannot use 'employee_id' because it's from the original table.
BThe query will fail without aliasing.
CThe outer query can use 'employee_id' if included in the derived table.
DThe average salary calculation will be incorrect.
💡 Hint
Refer to the concept that the outer query sees only columns output by the subquery (derived table).
Concept Snapshot
Subqueries in FROM create a temporary table (derived table) for the outer query.
Syntax: FROM (subquery) AS alias
The outer query uses alias to refer to subquery results.
Subquery runs first, then outer query processes its output.
Useful for complex queries needing intermediate results.
Full Transcript
This visual execution shows how a subquery inside the FROM clause runs first to produce a derived table. The outer query then uses this derived table to perform grouping and aggregation. We traced a query that calculates average salary per department by first selecting department and salary from employees as a derived table named 'dt'. The execution table shows each step: running the subquery, creating the derived table, grouping by department, calculating averages, and returning the final result. Variables track the subquery result, derived table availability, and average salary calculations. Key moments clarify why aliasing is required, the order of execution, and column visibility. The quiz tests understanding of these steps and effects of changing the subquery. The snapshot summarizes the concept and syntax for quick reference.