Anonymous
Anonymous

Reputation: 69

Replace value from one column with a value from another columns

|Name    | FamilyName |
+--------+------------+
Penelopa | Crow       |
Mandarin | Overflow   |

I want to read Penelopa from "Name" and replace Crow value from "FamilyName" with Penelopa in a single query.

I do know that the Name I'm interested to use would be Penelopa as I do something like, and it exist.

SELECT "Name" FROM MyTable WHERE "Name" = 'Penelopa';

Upvotes: 0

Views: 1471

Answers (2)

Kamil Gosciminski
Kamil Gosciminski

Reputation: 17157

It's a basic update statement:

UPDATE MyTable
SET "FamilyName" = "Name"
WHERE "Name" = 'Penelopa' AND "FamilyName" = 'Crow'

To be sure that we are not replacing all family names with the name penelopa, but only the one for familyname Crow, I've included this condition in the WHERE statement.

One more thing to note would be that creating tables and columns with quotation marks " only makes it harder to code so I would avoid that.


To see your changes immediately without typing another query, you might add RETURNING * clause at the end of UPDATE query like this:

UPDATE MyTable
SET "FamilyName" = "Name"
WHERE "Name" = 'Penelopa' AND "FamilyName" = 'Crow'
RETURNING *

Upvotes: 2

Kemal AL GAZZAH
Kemal AL GAZZAH

Reputation: 1037

This SQL script can do what do the update you want to do (replace table by your table name):

update table set FamilyName=Name where Name='Penelopa';

Upvotes: 0

Related Questions