How can I copy data from one column to another in the same table?

Sql

Sql Problem Overview


Is it possible to copy data from column A to column B for all records in a table in SQL?

Sql Solutions


Solution 1 - Sql

How about this

UPDATE table SET columnB = columnA;

This will update every row.

Solution 2 - Sql

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

Solution 3 - Sql

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Solution 4 - Sql

If you want to copy a column to another column with a different data type in PostgresSQL, you must cast/convert to the data type first, otherwise it will return

> Query 1 ERROR: ERROR: column "test_date" is of type timestamp without > time zone but expression is of type character varying LINE 1: update > table_name set test_date = date_string_col > ^ HINT: You will need to rewrite or cast the expression.

An example of converting varchar to timestamp:

update table_name set timestamp_col = date_string_col::TIMESTAMP;

An example of converting varchar to int:

update table_name set int_column = string_col::INTEGER;

but any column type(except file or the similar) can be copied to string(character varying) without cast the type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonneyView Question on Stackoverflow
Solution 1 - SqlAsh BurlaczenkoView Answer on Stackoverflow
Solution 2 - Sqldev4092View Answer on Stackoverflow
Solution 3 - SqlVayuj RajanView Answer on Stackoverflow
Solution 4 - SqlMuhammad Dyas YaskurView Answer on Stackoverflow