Bird
0
0

Consider the query:

medium📝 query result Q4 of 15
PostgreSQL - Subqueries in PostgreSQL
Consider the query:
SELECT d.name, (SELECT COUNT(*) FROM employees e WHERE e.department_id = d.id) AS emp_count FROM departments d;

What will this query return?
AEach employee name with their department name.
BA single row with total employees across all departments.
CAn error because subquery is not correlated.
DEach department name with the count of employees in that department.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the subquery correlation

    The subquery counts employees where e.department_id = d.id, linking to outer query's department.
  2. Step 2: Understand the output

    For each department, it returns the department name and employee count in that department.
  3. Final Answer:

    Each department name with the count of employees in that department. -> Option D
  4. Quick Check:

    Correlated subquery counts per department = Each department name with the count of employees in that department. [OK]
Quick Trick: Correlated subqueries compute per outer row values. [OK]
Common Mistakes:
  • Thinking subquery returns total count only once.
  • Assuming subquery is uncorrelated and causes error.
  • Confusing employee names with counts.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes