PostgreSQL’s Powerful New Join Type: LATERAL
PostgreSQL 9.3 has a new join type! Lateral joins arrived without a lot of fanfare, but they enable some powerful new queries that were previously only tractable with procedural code. In this post, I’ll walk through a conversion funnel analysis that wouldn’t be possible in PostgreSQL 9.2.
What is a LATERAL join?
The best description in the documentation comes at the bottom of the list of FROM clause options:
The
LATERAL
key word can precede a sub-SELECT FROM
item. This allows the sub-SELECT
to refer to columns ofFROM
items that appear before it in theFROM
list. (WithoutLATERAL
, each sub-SELECT
is evaluated independently and so cannot cross-reference any otherFROM
item.)
…
When aFROM
item containsLATERAL
cross-references, evaluation proceeds as follows: for each row of theFROM
item providing the cross-referenced column(s), or set of rows of multipleFROM
items providing the columns, theLATERAL
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).