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

I have a table with two DATETIME columns.

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

I need to write a query that will set all NULL rows for column B to the same values ​​in column A.

I tried this example , but SQL in the selected answer fails because MySQL Workbench does not seem to like FROM in UPDATE.

+71
sql mysql
Oct 19 '11 at 5:41
source share
5 answers

It looks like you only work in one table, so something like this:

update your_table set B = A where B is null 
+123
Oct 19 2018-11-11T00:
source share
 UPDATE YourTable SET ColumnB=ColumnA WHERE ColumnB IS NULL AND ColumnA IS NOT NULL 
+16
Oct 19 2018-11-11T00:
source share

I would do it like this:

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

COALESCE is a function that returns its first nonzero argument.

In this example, if B in the given string is not null, the update is no-op.

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

+13
Oct 19 '11 at 5:53
source share

I do not think another example is what you are looking for. If you are just updating one column from another column in the same table, you should use something like this.

 update some_table set null_column = not_null_column where null_column is null 
+4
Oct 19 2018-11-11T00:
source share

Here is sample code that can help you copy column A to column B:

 UPDATE YourTable SET ColumnB = ColumnA WHERE ColumnB IS NULL AND ColumnA IS NOT NULL; 
0
Oct. 25 '16 at 5:50
source share



All Articles