1

Please I have a table, with null values and I am trying to write an sql query to replace them with values from the previous row

table: customer

id value
001 34
002 Null
003 Null
004 Null
005 20
006 Null
007 Null
008 55

what I want to achieve

id value
001 34
002 20
003 20
004 20
005 20
006 55
007 55
008 55

thanks

2
  • in relational databases there is no inherent notion of previous row unless the table is sorted somehow. So how do you define the previous row? Commented Feb 14, 2022 at 14:55
  • 1
    lets assume the table is sorted in descending order, I will update it now Commented Feb 14, 2022 at 14:58

2 Answers 2

4

Using LAG with IGNORE NULLS

SELECT *, COALESCE(value, LAG(value) IGNORE NULLS OVER(ORDER BY id)) AS value
FROM customer
ORDER BY id;

LAG(previous)/LEAD(following) value

db<>fiddle demo

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the contribution, please can you help look into this? stackoverflow.com/questions/71111997/…
MySQL is far behind other RDBMS, didn't even know this existed. +1
@Lukasz, please this didnt seem to work properly especially for the once with 3 NULL values above them
@lee Please find attached demo. Here you could use LEAD or LAG but ORDER BY has to be DESC. If this operation has to be done per specific group then OVER(PARTION BY ... ORDER BY id)
0

A subquery to get the values from the immediate following row where value is not null should do the job:

select id,
(select value from customer where id >= c.id and value is not null
order by id limit 1) as value
from customer c
order by id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.