I have the following table:
create table table1
(
id serial,
workdate date,
col1 varchar,
col2 varchar,
col3 varchar
);
And I have inserted the following data:
insert into table1(id, workdate) values (DEFAULT, '01/12/2023');
Now I updated it, looking to the first null column of a sequence. For example: I run the following update:
update table1 set col1 = '12' where id = 1; /* there's no relation between col1 and any other data on this query. '12' is just a random value */
Now that I have updated it once, I want to create a query to look for the first NULL column and then update it. If col1 was NULL, then 12 would be put there. Or else, if col1 have some non-NULL value I want to update 12 in col2 (and so on…)
How can I do that I PostgreSQL? (Using Postgre 9.6)
I tried to use COALESCE to do that, however I get the exact reverse result that I’m looking for. Lacking ideas now (except to use a lot of CASE WHEN on my code – something that I’m trying not to do. Want to do something more elegant)
2
Answers
Try below query that updates the first
NULL
column in a row with a specifiedvalue ('12')
, using sequentialCASE
statements to check each column in order.It’s somewhat doable without an extensive
case
tree if you use arrays that offer:
slices. All you do is construct an array out of the row, slice it up to where the firstnull
is (array_position()
returns the first location of a given element), concatenate your desired element there with a||
, then add the remaining slice with another||
. Demo at db<>fiddle:You can achieve a similar effect with
jsonb
and related functions. That’s just to demonstrate it’s doable, not that it’s a good idea. It’s best to state what your actual problem is and how you see this kind of mechanism helping you arrive at a solution.