Reputation: 12439
Is it possible to have something like this
UPDATE TABLE foo
SET bar = 1
WHERE foo_bar = 'cat';
UPDATE TABLE foo
SET bar = 2
WHERE foo_bar = 'dog';
UPDATE TABLE foo
SET bar = 3
WHERE foo_bar = 'elephant';
in one statement?
Upvotes: 1
Views: 37
Reputation: 19653
Use a CASE
UPDATE foo SET foo_bar =
CASE
WHEN bar = 1 THEN 'dog'
WHEN bar = 2 THEN 'cat'
WHEN bar = 3 THEN 'elephant'
END;
Demo: db<>fiddle
Upvotes: 1
Reputation:
You can use a CASE expression
update foo
set bar = case foo_bar
when 'cat' then 1
when 'dog' then 2
when 'elephant' then 3
end
where foo_bar in ('cat', 'dog', 'elephant');
Alternatively this could be done using a VALUES clause to avoid repeating the values.
update foo
set bar = t.new_bar
from t
values
('cat', 1),
('dog', 2),
('elephant', 3)
) as t(foobar, new_bar)
where t.foobar = foo.foo_bar;
Upvotes: 0