Search code examples
sqlpostgresqlsql-updatesubquery

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.


Solution

  • 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.