sqloracle-databasejoinoracle11glateral-join

How to use Lateral join in Oracle?


I am trying to use Lateral Join in Oracle(Oracle Database 11g Release 11.2.0.1.0) but it is giving some error. I have followed this link

https://oracle-base.com/articles/12c/lateral-inline-views-cross-apply-and-outer-apply-joins-12cr1#lateral-inline-views and applied it on the same data but still it isn't working. Can someone figure out the issue?

SELECT department_name, employee_name
FROM   departments d,
     LATERAL(SELECT employee_name FROM employees e WHERE e.department_id = d.department_id) 
ORDER BY 1, 2; 

Adding further details for clarify why I need a lateral join: I have a table e.g

ID  Length  
1   20
2   50
3   30
4   40
5   20
6   80

and I want to add another column of the sum of the length of records that have ID less than current row's ID i.e

ID  Length   Sum 
1   20       NULL
2   50       20
3   30       70
4   40       100
5   20       140
6   80       160

With the Lateral JOIN it could have be very simple for example

select A.ID,A.length,Sum from Table A,
Lateral (select sum(B.length) as Sum from Table B where B.id<A.id);

So is there is any alternative to this?


Solution

  • The LATERAL does not work because it is introduced from version 12. As GMB say. This is one aproach to the problem you have:

    SELECT t1.id, t3.name
    FROM   test t1
    left join (select id, name from test t2) t3
    on t1.id = t3.id
    order by 2, 1
    

    Here is a DEMO

    Or maybe you wanted something like this:

    select
       t1.id,
       t1.name
    from   test t1
           where t1.name in (select t2.name
                    from   test t2
                    where  t2.id = t1.id)
    order by 1, 2;
    

    If none of the above approaches does not help you (it is not what you wanted), then there is another way. You can "enable" LATERAl in your old Oracle 11 version like this:

    alter session set events '22829 trace name context forever';
    

    You see, this option/feature did existed in older versions but it was not "enabled". Here is a DEMO showing that your statement on your example data first trhows an error and then after this alter session command, it works.

    If you want a query that will give you a resul as in your question and will work on 11g then you can use this:

    select ID, Length, LAG(ACUM) OVER (order by ID) sum
    from (SELECT ID
                 , length
                 , Sum(length) OVER (ORDER BY id) as ACUM
          FROM   Table1 
          group by ID, length)
    

    And the same thing can be done in a "more easy" way:

    SELECT id,
           length,
           (SELECT Sum(length)
            FROM   Table1 b
            WHERE  a.id > b.id) ACUM
    FROM   Table1 a 
    

    Here is the demo where you can see this query returns the same ersults.

    Hope this helps.