I was looking to update fields on a row in PostgreSQL only if the fields were null. Otherwise I would overwrite what’s already in the row.
My update
looks as simple as this:
UPDATE public.people
SET flag=$flag,
name=$name,
surname=$surname
WHERE id_dt=$id_dt;
Can you help?
2
Answers
Here you go:
Coalesce() returns the first non-null value, so
name
if it's already there, or$name
(that is your new value)Looks like you could start a transaction with 2 statemnts and add a where clause that ignores correct rows:
If you go with the coalesce option like stated in a simpling answer, you can still add a
where name is null or surname is null
clause to reduce the working set.Side note: I see you use
$
like it was used in string interpolation. Always prefer to use prepared statements to avoid attacks via sql injection.