Search code examples
sqlsqliteinterpolationsparse-data

How to replace NULL with the previous value?


My table:

field5 field19
Dr 1
NULL 2
NULL 3
Td 4
Td 5
NULL 6

SQL query should give following result:

field5 field19
Dr 1
Dr 2
Dr 3
Td 4
Td 5
Td 6

Solution

  • Window function would help :

    select *,  
          max(field5) over (order by field19)
    from table t;
    

    You can also use correlated subquery :

    select t.*,
           (select t1.field5 
            from table t1 
            where t1.field19 <= t.field19 and t1.field5 is not null
            order by t1.field19 desc 
            limit 1
           )
    from table t;