Bird
0
0

Consider tables employees(id, name) and sales(employee_id, total_sale). What does this query return?

medium📝 query result Q4 of 15
PostgreSQL - Subqueries in PostgreSQL
Consider tables employees(id, name) and sales(employee_id, total_sale). What does this query return?

SELECT e.name, s.max_sale FROM employees e CROSS JOIN LATERAL (SELECT MAX(total_sale) AS max_sale FROM sales WHERE employee_id = e.id) s;
AAll employees paired with every sale they made, resulting in multiple rows per employee.
BEach employee's name with their highest sale amount, including employees with no sales showing NULL.
COnly employees who have made sales, showing their highest sale amount.
DA list of all sales with employee names repeated for each sale.
Step-by-Step Solution
Solution:
  1. Step 1: Understand CROSS JOIN LATERAL

    The LATERAL subquery runs for each employee, calculating MAX(total_sale) for that employee.
  2. Step 2: Analyze the subquery result

    MAX(total_sale) returns NULL if no sales exist for that employee.
  3. Step 3: Result interpretation

    The query returns each employee's name with their highest sale or NULL if none.
  4. Final Answer:

    Each employee's name with their highest sale amount, including employees with no sales showing NULL. correctly describes the output.
  5. Quick Check:

    CROSS JOIN LATERAL runs subquery per row, preserving all employees [OK]
Quick Trick: CROSS JOIN LATERAL preserves all rows, subquery can return NULL [OK]
Common Mistakes:
  • Assuming employees without sales are excluded
  • Confusing CROSS JOIN LATERAL with INNER JOIN
  • Thinking the subquery returns multiple rows

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes