oracle11gmaxoracle-analytics

MAX with Inner join VS rank() over


I am trying to fetch maximum balance for given account

ACCT_BALANCE table:
ACCOUNT_JOIN,BALANCE_UPDATE_DATE,ACCT_VALUE
1   11:49 AM 3/21/2017  1000
1   10:49 AM 5/29/2017  2121
2   11:49 AM 3/29/2017  3332    
2   13:21 AM 3/33/2017  110
3   11:50 AM 4/4/2017   888 
4   10:49 AM 3/29/2017  66  
4   11:50 AM 3/3/2017   57000
4   10:49 AM 2/29/2017  2265
4   13:21 AM 3/2/2017   555 
4   11:50 AM 8/9/2017   555

for example, max balance for account join 1 is 2121 from 5/29/2017

Performance wise what will be better? using MAX with Inner join or rank() over?

CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
SELECT ACCT_VALUE,ACCOUNT_JOIN
  FROM ( 
        SELECT ACCT_VALUE,ACCOUNT_JOIN,
           rank() over (partition by ACCOUNT_JOIN order by BALANCE_UPDATE_DATE desc) rnk
        FROM ACCT_BALANCE  
      )
 WHERE rnk = 1
/


CREATE OR REPLACE VIEW MAX_VAL_VIEW
AS
              SELECT A.ACCT_VALUE ,A.ACCOUNT_JOIN 
              FROM ACCT_BALANCE A
                WHERE A.BALANCE_UPDATE_DATE = (
                    SELECT max(B.BALANCE_UPDATE_DATE)
                    FROM ACCT_BALANCE B
                    WHERE B.ACCOUNT_JOIN = A.ACCOUNT_JOIN
        )
/

Solution

  • You could also use the last function:

    select max(acct_value) keep (dense_rank last order by balance_update_date) as acct_value,
      account_join
    from acct_balance
    group by account_join;
    
    ACCT_VALUE ACCOUNT_JOIN
    ---------- ------------
          2121            1
           110            2
           888            3
           555            4
    

    (using modified date/times to make them all valid).

    Either that or the rank() approach should beat the max(B.BALANCE_UPDATE_DATE) approach, as they only hit the table once. You can look at the execution plans for all three queries to see how the optimiser treats them - which indexes (if any) they use, how many full table scans, etc.