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
LATERALkey word can precede a sub-SELECT FROMitem. This allows the sub-SELECTto refer to columns ofFROMitems that appear before it in theFROMlist. (WithoutLATERAL, each sub-SELECTis evaluated independently and so cannot cross-reference any otherFROMitem.)
…
When aFROMitem containsLATERALcross-references, evaluation proceeds as follows: for each row of theFROMitem providing the cross-referenced column(s), or set of rows of multipleFROMitems providing the columns, theLATERALitem 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).