I have created table and inserted values as below.
create table mytable (id INT, col1 INT, col2 INT, col3 INT);
insert into mytable values
(1,1,1,NULL),
(2,1,NULL,NULL);
What I want to do is update col2 if col1 is not null, update col3 if col2 is not null and so on… BUT only one column to update.
Consider I want to update data for id=2, then only col2 should be updated and not col2, col3 as both are null.
When I tried with below query, then all columns get updated.
update myTable set
col1 = ( IF (col1 is null, 9, col1) ),
col2 = ( IF (col2 is null, 9, col2) ),
col3 = ( IF (col3 is null, 9, col3) );
What should be done so that only one column gets updated.
It seems your query is an extension to Update MySql Field (if field is not empty, go to next one)
You need to set column values checking in the reverse order.
Example Table:
You can also use
iffunction as an alternative tocasestatement.