Bird
0
0

How can you optimize a correlated subquery that counts employees per department to avoid repeated execution?

hard📝 Application Q9 of 15
PostgreSQL - Subqueries in PostgreSQL
How 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.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the problem with correlated subqueries

    They run once per outer row, causing repeated work.
  2. Step 2: Use JOIN and GROUP BY to calculate counts once

    JOIN with GROUP BY aggregates counts per department efficiently.
  3. Final Answer:

    Rewrite using JOIN and GROUP BY to calculate counts once per department. -> Option B
  4. Quick 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.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes