Search code examples
sqlrpgle

Difference between SQL statements


I have come across two versions of an SQLRPGLE program and saw a change in the code as below:

Before:

Exec Sql SELECT 'N' 
         INTO :APRFLG            
         FROM LG751F T1 
         INNER JOIN LG752F T2 
           ON T1.ISBOLN  =  T2.IDBOLN AND   
              T1.ISITNO  =  T2.IDMDNO 
        WHERE T2.IDVIN   =  :M_VIN AND      
              T1.ISAPRV  <> 'Y';            

After:

Exec Sql SELECT case 
                  when T1.ISAPRV <> 'Y' then 'N'                        
                  else T1.ISAPRV                  
                end as APRFLG                          
         INTO :APRFLG                                  
         FROM LG751F T1                                
         join LG752F T2 
           ON T1.ISBOLN =  T2.IDBOLN AND   
              T1.ISITNO =  T2.IDMDNO       
        WHERE T2.IDVIN  =  :M_VIN AND                 
              T1.ISAPRV <> 'Y'                        
     group by T1.ISAPRV;                 

Could you please tell me if you see any difference in how the codes would work differently? The second SQL has a group by which is supposed to be a fix to avoid -811 SQLCod error. Apart from this, do you guys spot any difference?


Solution

  • They are both examples of poor coding IMO.

    The requirement to "remove duplicates" is often an indication of a bad statement design and/or a bad DB design.

    You appear to be doing an existence check, in which case you should be making use of the EXISTS predicate.

    select 'N' into :APRFLG
    from sysibm.sysdummy1
    where exists (select 1
                  FROM LG751F T1 
                       INNER JOIN LG752F T2 
                         ON T1.ISBOLN  =  T2.IDBOLN    
                            AND T1.ISITNO  =  T2.IDMDNO 
                  WHERE 
                    T2.IDVIN   =  :M_VIN 
                    AND T1.ISAPRV  <> 'Y');
    

    As far as the original two statements, besides the group by, the only real difference is moving columns from the JOIN clause to the WHERE clause. However, the query engine in Db2 for i will rewrite both statements equivalently and come up with the same plan; since an inner join is used.

    EDIT : as Mark points out, there JOIN and WHERE are the same in both the OP's statements. But I'll leave the statement above in as an FYI.