PostgreSQL - Subqueries in PostgreSQLHow can you optimize a correlated subquery that counts employees per department to avoid repeated execution?AAdd DISTINCT inside the subquery to reduce duplicates.BRewrite using JOIN and GROUP BY to calculate counts once per department.CUse a window function inside the subquery.DReplace the subquery with a scalar function call.Check Answer
Step-by-Step SolutionSolution:Step 1: Identify the problem with correlated subqueriesThey run once per outer row, causing repeated work.Step 2: Use JOIN and GROUP BY to calculate counts onceJOIN with GROUP BY aggregates counts per department efficiently.Final Answer:Rewrite using JOIN and GROUP BY to calculate counts once per department. -> Option BQuick Check:Optimization by JOIN and GROUP BY = Rewrite using JOIN and GROUP BY to calculate counts once per department. [OK]Quick Trick: JOIN with GROUP BY often replaces correlated subqueries for efficiency. [OK]Common Mistakes:Using DISTINCT does not reduce repeated executions.Window functions don't replace correlated subqueries here.Scalar functions may not improve performance.
Master "Subqueries in PostgreSQL" in PostgreSQL9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More PostgreSQL Quizzes Aggregate Functions and GROUP BY - JSON aggregation with JSON_AGG - Quiz 4medium Aggregate Functions and GROUP BY - ROLLUP and CUBE for hierarchical totals - Quiz 6medium Common Table Expressions - CTE vs subquery performance - Quiz 9hard Common Table Expressions - CTE with INSERT, UPDATE, DELETE (writable CTEs) - Quiz 9hard Full-Text Search - Ranking with ts_rank - Quiz 4medium JSON and JSONB - JSONB existence (?) operator - Quiz 4medium Views and Materialized Views - Updatable views - Quiz 8hard Views and Materialized Views - Materialized view vs regular view decision - Quiz 10hard Views and Materialized Views - Views with CHECK OPTION - Quiz 10hard Window Functions in PostgreSQL - Window frame (ROWS BETWEEN, RANGE BETWEEN) - Quiz 14medium