Coding Bits
April 23rd, 2024 Databases

PostgreSQL LATERIAL Joins

Someone shared with me the LATERIAL join type supported by PostgreSQL. He described it as a "for each" built into SQL:

When a FROM item contains LATERAL cross-references, evaluation proceeds as follows: for each row of the FROM item providing the cross-referenced column(s), or set of rows of multiple FROM items providing the columns, the LATERAL item is evaluated using that row or row set's values of the columns. The resulting row(s) are joined as usual with the rows they were computed from. This is repeated for each row or set of rows from the column source table(s).

Here's an example on how they look from the manual:

SELECT * FROM foo, 
LATERAL (SELECT * FROM bar WHERE bar.id = foo.bar_id) ss;

This is perfect. Many a times I wish there was a way to do this in SQL. Most of the times I just make multiple calls to the database. The obvious cost in doing so is the round-trip between the client and the server. So it's nice to see a native way to do this in PostgreSQL.

I've yet to try this out but I'll make sure to do so next time I need something like this.