Which of the following is the correct syntax to use a LATERAL join in PostgreSQL?
easy📝 Syntax Q12 of 15
PostgreSQL - Joins in PostgreSQL
Which of the following is the correct syntax to use a LATERAL join in PostgreSQL?
ASELECT a.id, b.value FROM table_a a JOIN (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true;
BSELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true;
CSELECT a.id, b.value FROM table_a a LEFT JOIN LATERAL table_b b ON b.a_id = a.id;
DSELECT a.id, b.value FROM table_a a CROSS JOIN table_b b WHERE b.a_id = a.id;
Step-by-Step Solution
Solution:
Step 1: Identify correct LATERAL syntax
LATERAL must be explicitly stated before the subquery or table function to allow referencing outer query columns.
Step 2: Check each option
SELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; correctly uses JOIN LATERAL with a subquery referencing outer alias 'a'. SELECT a.id, b.value FROM table_a a JOIN (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; misses LATERAL keyword. SELECT a.id, b.value FROM table_a a LEFT JOIN LATERAL table_b b ON b.a_id = a.id; uses LATERAL but tries to join a table directly without subquery syntax. SELECT a.id, b.value FROM table_a a CROSS JOIN table_b b WHERE b.a_id = a.id; uses CROSS JOIN without LATERAL, so no correlation.
Final Answer:
SELECT a.id, b.value FROM table_a a JOIN LATERAL (SELECT value FROM table_b WHERE b.a_id = a.id) b ON true; -> Option B
Quick Check:
Correct LATERAL syntax includes keyword before subquery [OK]
Quick Trick:LATERAL keyword must precede subquery to access outer columns [OK]
Common Mistakes:
Omitting LATERAL keyword before subquery
Using regular JOIN without correlation
Trying to join tables directly without subquery
Master "Joins in PostgreSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently