HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Update column with value of another column or another column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
updatecolumnwithvalueanother

Problem

With PostgreSQL (I'm using the version 9.1) is it possible to do mass update with a single query a column value with the value of another column, but if the other column value is null, to use the value of a third column, and if the third one is absent to use the current datetime (all the column have type timestamp)

I need to change

columnA columnB columnC
null foo bar
null null baz
null null null

to

columnA columnB columnC
foo foo bar
baz null baz
quz null null

where quz is the current datetime.

Solution

You can use COALESCE() function to do the update:

UPDATE ...
SET columnA = COALESCE(columnB, columnC, now());


COALESCE will return the first non-null value in the list that you provide.

Code Snippets

UPDATE ...
SET columnA = COALESCE(columnB, columnC, now());

Context

StackExchange Database Administrators Q#120635, answer score: 18

Revisions (0)

No revisions yet.