Bird
0
0

Consider these tables:

medium📝 query result Q5 of 15
PostgreSQL - Joins in PostgreSQL
Consider these tables:
departments(id, name)
employees(id, dept_id, salary)
What does this query return?
SELECT d.name, e.salary FROM departments d JOIN LATERAL (SELECT salary FROM employees WHERE dept_id = d.id ORDER BY salary DESC LIMIT 1) e ON true;
ADepartments with employees earning below average
BEach department with its highest employee salary
CAll employees with their department names
DDepartments without employees
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the LATERAL subquery

    It selects the highest salary per department by ordering salaries descending and limiting to 1.
  2. Step 2: Understand the join effect

    Each department joins to one employee salary: the highest in that department.
  3. Final Answer:

    Each department with its highest employee salary -> Option B
  4. Quick Check:

    LATERAL with ORDER BY and LIMIT 1 returns top value per group [OK]
Quick Trick: Use LATERAL with ORDER BY and LIMIT 1 for top per group [OK]
Common Mistakes:
  • Thinking it returns all employees
  • Assuming departments without employees appear
  • Confusing join with aggregation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes