Search code examples
sqlnullhsqldbcoalesce

HSQLDB query to replace a null value with a value derived from another record


This is a small excerpt from a much larger table, call it LOG:

RN EID FID FRID TID TFAID  
1 364   509 7045    null    7452  
2 364   509 7045    7452    null  
3 364   509 7045    7457    null  
4 375   512 4525    5442    5241  
5 375   513 4525    5863    5241  
6 375   515 4525    2542    5241  
7 576   621 5632    null    5452  
8 576   621 5632    2595    null  
9 672   622 5632    null    5966  
10 672  622 5632    2635    null  

I would like a query that will replace the null in the 'TFAID' column with the value from the 'TFAID' column from the 'FID' column that matches.

Desired output would therefore be:

RN EID FID FRID TID TFAID  
1 364   509 7045    null    7452  
2 364   509 7045    7452    7452  
3 364   509 7045    7457    7452  
4 375   512 4525    5442    5241  
5 375   513 4525    5863    5241  
6 375   515 4525    2542    5241  
7 576   621 5632    null    5452  
8 576   621 5632    2595    5452  
9 672   622 5632    null    5966  
10 672  622 5632    2635    5966 

I know that something like

    SELECT RN, 
        EID, 
        FID, 
        FRID, 
        TID, 
        (COALESCE TFAID, {insert clever code here}) AS TFAID
    FROM LOG

is what I need, but I can't for the life of me come up with the clever bit of SQL that will fill in the proper TFAID.


Solution

  • HSQLDB supports SQL features that can be used as alternatives. These features are not supported by some other databases.

    CREATE TABLE LOG (RN INT, EID INT, FID INT, FRID INT, TID INT, TFAID INT);
    
    -- using LATERAL
    SELECT l.RN, l.EID, l.FID, l.FRID, l.TID, 
       COALESCE(l.TFAID, f.TFAID) AS TFAID
       FROM LOG l , LATERAL (SELECT MAX(TFAID) AS TFAID FROM LOG f WHERE f.FID = l.FID) f
    
    -- using scalar subquery
    SELECT l.RN, l.EID, l.FID, l.FRID, l.TID, 
       COALESCE(l.TFAID, (SELECT MAX(TFAID) AS TFAID FROM LOG f WHERE f.FID = l.FID)) AS TFAID
       FROM LOG l