SQL set values of one column equal to values of another column in the same table

MysqlSql

Mysql Problem Overview


I have a table with two DATETIME columns.

One of them is never NULL, but one of them is sometimes NULL.

I need to write a query which will set all the NULL rows for column B equal to the values in column A.

I have tried https://stackoverflow.com/questions/707371/sql-update-set-one-column-to-be-equal-to-a-value-in-a-related-table-referenced-b">this example but the SQL in the selected answer does not execute because MySQL Workbench doesn't seem to like the FROM in the UPDATE.

Mysql Solutions


Solution 1 - Mysql

Sounds like you're working in just one table so something like this:

update your_table
set B = A
where B is null

Solution 2 - Mysql

I would do it this way:

UPDATE YourTable SET B = COALESCE(B, A);

COALESCE is a function that returns its first non-null argument.

In this example, if B on a given row is not null, the update is a no-op.

If B is null, the COALESCE skips it and uses A instead.

Solution 3 - Mysql

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

Solution 4 - Mysql

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

update some_table set null_column = not_null_column where null_column is null

Solution 5 - Mysql

Here is sample code that might help you coping Column A to Column B:

UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;

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
Questionuser1002358View Question on Stackoverflow
Solution 1 - Mysqlmu is too shortView Answer on Stackoverflow
Solution 2 - MysqlBill KarwinView Answer on Stackoverflow
Solution 3 - MysqlIcarusView Answer on Stackoverflow
Solution 4 - MysqlrwilliamsView Answer on Stackoverflow
Solution 5 - MysqlWaruna ManjulaView Answer on Stackoverflow