How can I swap two values from particular column in a table in Postgres?
update the_table
set name = case id
when 1 then (select name from the_table where id = 2)
when 2 then (select name from the_table where id = 1)
end
where id in (1,2);
This assumes that id
is unique (e.g. the primary key)
One more way, which can be modified easily to do more complicated changes (e.g. swap multiple couples or move values from 1->2->3->1, update multiple columns, etc.):
with changes (update_id, take_value_from_id) as
( values
(1, 2), -- update row with id=1 from row with id=2
(2, 1) -- update row with id=2 from row with id=1
),
data as
( select c.update_id, val.name
from changes as c
join the_table as val on val.id = c.take_value_from_id
)
update the_table as upd
set name = d.name
from data as d
where upd.id = d.update_id ;
Why not just swap the IDs instead of the value(s)? Or do the other columns have to remain as they were?
Anyway, in case someone else reads this question and is looking for this, it's just:
select case id when 1 then 2 when 2 then 1 else id end as id, ...other columns... from ...table...;
or as an update:
update ...table... set id = (case id when 1 then 2 when 2 then 1 else id end);
(I can never remember if the else id
clause is needed.)