single
Using Inner Subqueries in the FROM Section
Swipe to show menu
An inner subquery creates a table with which you then perform operations in the outer query.
From this, you can conclude that you can also use an inner query within the FROM section to select something from this table.
Consider an example where you need to work with employees whose salary is above a certain value. But instead of a WHERE clause, you should use an inner query:
123456SELECT * FROM ( SELECT * From employees WHERE salary >= 70000 ) AS high_salary_employees
A new table has been created using an inner subquery with which you can work and gather information.
Notice that for such a table, it's essential to provide an alias.
When might this be useful?
Such a query is highly readable; sometimes, it can replace a WHERE clause.
Additionally, if you need to work not with the entire table but only with a filtered part, an inner subquery within the FROM section can be extremely handy.
Swipe to start coding
Your task is to retrieve the average budget (budget column) for all managerial departments from the department table. Use an inner subquery in the FROM section to filter only the managerial type of department. Also, use the alias manager_departments for this table so the task is checked correctly.
The response should have only one column, average_budget. This is an alias for the aggregate function AVG().
This task could also be done using a WHERE clause, but we use a nested query here to practice this syntax, which will be useful for solving more complex problems in the future.
Brief Instructions
- Retrieve the average value of the
budgetcolumn. - Assign the alias
average_budgetto that column. - In the
FROMclause, you need to write a nested query. - In the nested query, select all columns from the
departmenttable. - In the nested query, use the
WHEREclause with the conditiontype = 'manager'. - Assign the alias
manager_departmentsto the nested query.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat