SQL - SubqueriesHow can you optimize a correlated subquery that calculates the average salary per department for a large employee table?ARewrite the subquery as a scalar subquery without correlationBPrecompute average salaries per department in a temporary table and join itCUse a correlated subquery with an index on employee nameDRemove the subquery and use a WHERE clause onlyCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand correlated subquery costCorrelated subqueries run repeatedly, which is expensive on large tables.Step 2: Use precomputed aggregationPrecomputing averages per department in a temp table and joining reduces repeated calculations.Final Answer:Precompute average salaries per department in a temporary table and join it -> Option BQuick Check:Precompute aggregates to optimize correlated subqueries [OK]Quick Trick: Replace repeated subqueries with joins on precomputed results [OK]Common Mistakes:MISTAKESIgnoring performance impact of correlated subqueriesUsing indexes on irrelevant columnsRemoving subquery without replacement
Master "Subqueries" in SQL9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More SQL Quizzes Aggregate Functions - COUNT function behavior - Quiz 12easy GROUP BY and HAVING - GROUP BY single column - Quiz 4medium INNER JOIN - INNER JOIN syntax - Quiz 9hard INNER JOIN - INNER JOIN with ON condition - Quiz 4medium LEFT and RIGHT JOIN - LEFT JOIN vs RIGHT JOIN decision - Quiz 10hard Set Operations - EXCEPT (MINUS) for differences - Quiz 11easy Subqueries - Subquery with EXISTS operator - Quiz 10hard Table Constraints - Composite primary keys - Quiz 10hard Views - Updatable views and limitations - Quiz 14medium Views - Updatable views and limitations - Quiz 3easy