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

How can I swap two values from particular column in a table in Postgres?

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

Problem

Consider a table test contains an attributes of id and name.

The values for that.

Id   |   Name
1    |   Raj
2    |   Kumar


From the above sample table, I know only the id, So through the Id I need to swap the name, like given below,

Id   |   Name
1    |   Kumar
2    |   Raj

Solution

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)

Code Snippets

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);

Context

StackExchange Database Administrators Q#131118, answer score: 13

Revisions (0)

No revisions yet.