qake90
qake90

Reputation: 13

SQL - Copy data from one column to another in the same table

I have a table with 1000+ rows and I am trying to copy data from one column to another, for all rows.

This is my table "Invoice":

example1 example 2
A NULL
B NULL
C NULL

Expected end result should be:

example1 example 2
A A
B B
C C

What I tried so far:

UPDATE "Invoice" 
SET "example1" = copiedData
FROM (SELECT "example2" FROM "Invoice") AS copiedData;

This does update all rows but the issue is that it does not update row for row, instead it picks up a random row from the sub query and applies it to all rows.

Example of how the current result looks like:

example1 example 2
A B
B B
C B

What am I missing here?

Thank you.

Upvotes: 1

Views: 4745

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269853

What you want is much simpler:

UPDATE "Invoice" 
    SET "example2" = "example1";

Note: I would strongly encourage you to remove the double quotes! Don't escape column names -- it just makes it harder to write and to read the code.

Upvotes: 0

You just need to update Invoice table's example2 column with example1.

UPDATE Invoice 
SET example2 = example1;

If you only want to update example2 column when it's null then you will need a where clause also.

UPDATE Invoice 
SET example2 = example1 where example2 is null;

Upvotes: 1

Related Questions