Bird
0
0

Examine this query:

medium📝 Debug Q6 of 15
PostgreSQL - Joins in PostgreSQL
Examine this query:
SELECT c.name, o.amount FROM customers c JOIN LATERAL (SELECT amount FROM orders WHERE customer_id = c.id) o ON true;

What is the likely cause of an error?
AThe subquery returns multiple rows without LIMIT, causing ambiguity.
BThe ON clause is missing a join condition referencing both tables.
CThe LATERAL keyword cannot be used with JOIN.
DThe subquery in LATERAL does not have an alias.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the subquery

    The subquery selects amount from orders where customer_id = c.id. If multiple orders exist per customer, multiple rows are returned.
  2. Step 2: Understand JOIN behavior

    JOIN expects one row per join key unless using JOIN LATERAL with LIMIT or aggregation.
  3. Step 3: Identify error cause

    Without LIMIT or aggregation, the subquery returns multiple rows, causing an error.
  4. Final Answer:

    The subquery returns multiple rows without LIMIT, causing ambiguity. -> Option A
  5. Quick Check:

    Does the subquery return multiple rows? Yes. [OK]
Quick Trick: Subquery must return one row per outer row [OK]
Common Mistakes:
  • Assuming ON clause must have join condition referencing both tables
  • Thinking LATERAL cannot be used with JOIN
  • Forgetting to alias the subquery (which is done here)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes