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

后端 未结 4 1098
花落未央
花落未央 2020-11-21 08:58

Since Postgres came out with the ability to do LATERAL joins, I\'ve been reading up on it, since I currently do complex data dumps for my team with lots of inef

4条回答
  •  一整个雨季
    2020-11-21 09:27

    The difference between a non-lateral and a lateral join lies in whether you can look to the left hand table's row. For example:

    select  *
    from    table1 t1
    cross join lateral
            (
            select  *
            from    t2
            where   t1.col1 = t2.col1 -- Only allowed because of lateral
            ) sub
    

    This "outward looking" means that the subquery has to be evaluated more than once. After all, t1.col1 can assume many values.

    By contrast, the subquery after a non-lateral join can be evaluated once:

    select  *
    from    table1 t1
    cross join
            (
            select  *
            from    t2
            where   t2.col1 = 42 -- No reference to outer query
            ) sub
    

    As is required without lateral, the inner query does not depend in any way on the outer query. A lateral query is an example of a correlated query, because of its relation with rows outside the query itself.

提交回复
热议问题