I have the following table:
create table table1
(
id serial,
workdate date,
tanknum1 integer,
tanknum2 integer,
tanknum3 integer,
tank1startingvalue float,
tank2startingvalue float,
tank3startingvalue float,
tank1endvalue float,
tank2endvalue float,
tank3endvalue float
);
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 tanknum1 = 8 where id = 1;
Now that I have updated it once, I want to create a query to look for the first NULL column and then update it. For example: I already have the tanknum1 non-NULL, so when I update the query using date 01/12/2023 I want it to look for tanknum2 and tanknum3. Tanknum2 is NULL? Ok, then I'll change this value. tanknum2 is non-NULL? All right, let me check tanknum3. Is it null? (and so forth. The edge case is: if i get to tanknum3 and it's already non-NULL I don't want to update it)
I'm doing this to control a gas station inventory and I'm not able to upgrade the Postgre version. This information is arriving to me via .txt file, only with the tank number, date, starting and ending value.
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)
Coalesce()seems to be usable for what you described:update table1 set col1 = coalesce(col1,'12') where id = 1;if col1 is not null, then it remains unchanged. If it is, it's set to '12'. Problem is, if you target all columns this way, they'll all get updated independently, not just the first one. Can you provide some additional context on what it is you're trying to achieve with this? What's the actualy problem you're trying to solve with this?col1,col2, etc., form a repeating group, which should not exist in a normalized database; however, there could be valid reasons to violate this guideline. Ifcol2is non-NULL, mustcol1also be non-NULL? If so, then constraints should be in place to enforce that rule. Please update your post with the use case and data integrity rules.Using Postgre 9.6you must be joking. That version was released back in 2016 and is EOL since 2021. Do yourself a favor and upgrade to a recent (supported) version. For identity columns, use IDENTITY: postgresql.org/docs/current/sql-createtable.htmlcol1,col2, andcol3are already all non-NULL? It's very important to consider edge cases and possible failure modes and to fully specify expected behavior.COALESCEis essentially syntactic sugar for aCASEexpression to find the first non-NULL value, so it's only more elegant by virtue of brevity.