Skip to content

sql: support lateral joins #24560

@knz

Description

@knz

A join is "lateral" when its right operand depends on the left operand.

Lateral joins are one of the ways a subquery or relational expression can be correlated.

Lateral joins occur:

  • in the regular join syntax with the keyword "LATERAL", e.g. SELECT * FROM a, LATERAL b
  • implicitly when using a SRF in the select render position and one of the SRF argument uses a column name from one of the existing FROM tables, e.g. SELECT generate_series(v) FROM kv
  • also needed for common uses of jsonb_object_keys(), see sql: cannot project json_object_keys() on a json column #26110

Note: LATERAL in the join syntax changes the name resolution rules!

For example, the following two queries have very different behavior:

SELECT
   (SELECT a FROM db1.ab, LATERAL (SELECT * FROM kv WHERE v = b))
          -- v = b refers to "b" in db1.ab
FROM db2.ab

vs.

SELECT
   (SELECT a FROM db1.ab, (SELECT * FROM kv WHERE v = b))
          -- v = b refers to "b" in db2.ab!
FROM db2.ab

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-sql-optimizerSQL logical planning and optimizations.A-sql-semanticsC-enhancementSolution expected to add code/behavior + preserve backward-compat (pg compat issues are exception)X-anchored-telemetryThe issue number is anchored by telemetry references.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions