Explain Codes LogoExplain Codes Logo

What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?

sql
join
subquery
performance
Nikita BarsukovbyNikita Barsukov·Jan 15, 2025
TLDR

When you feel tied down by a subquery, a LATERAL JOIN swoops in like a knight-in-coding-armor, enabling you to harness column values of preceding tables in your **JOIN**s. Let's peek at the events table with our handy-dandy function get_latest_event_info that requires an event_id:

SELECT e.id, e.name, li.info FROM events e, LATERAL get_latest_event_info(e.id) AS li;

It's like get_latest_event_info and e.id are BFFs, they always stick together thanks to LATERAL. 🌀

When to go LATERAL

Just like different superhero capes for different days, LATERAL JOINs and subqueries have their unique shine moments.

Unleash the LATERAL power for multiple columns

You've got a function that returns multiple columns, or a set-returning function like unnest() up your sleeve? Perfect time to let LATERAL steal the spotlight.

Surviving the zero-row wilderness

Set-returning functions can sometimes come back empty handed (yeah, it's a bummer). If this makes your main row vanish, perform some **``LEFT JOIN LATERAL``` magic to keep it around. 🎩

SPEED Racer LATERAL

Waiting around isn't fun. Whether it's a coffee machine or SQL query, efficiency matters. LATERAL thoughts can sometimes make your subquery execution go from 🐢 to 🚀.

Watch out for LATERAL tripwires

Like every SQL superhero, LATERAL can sometimes stumble. Be wary of its quirks and don't tripped up.

Careful with JOIN conditions

LATERAL joins can be all, "I'M DONE! NO MORE CONDITIONS TO JOIN". But don't let it fool you. Always scan for the join condition in INNER / OUTER LATERAL joins.

Understanding plan costs

Budgeting is essential, be it personal finance or SQL queries. LATERAL can evaluate subqueries multiple times, adding to your overall resource costs. Be cautious of SQL debt!

Use it wisely

Not every problem needs a toolbox. Sometimes, a simple JOIN, WHERE or UNION may suffice over the rights of LATERAL passage.

LATERAL synergy with SQL weapons

Dual wield LATERAL with other SQL weapons to unlock advanced strategies.

ZERO problems with COALESCE and CASE

Walloped by zero-row sets from set-returning functions? Use the infinity stones! Or.... just stick with COALESCE or CASE.

Like paper to a correlated subquery's rock

Remember rock-paper-scissors? Using LEFT JOIN LATERAL ... ON true can out perform correlated subqueries like paper over rock.

Code readability, your SQL EndGame

LATERAL is like a readability stone for your SQL universe. Complex extractions look less intimidating, making your SQL scripts Thanos-proof.