Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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

like image 673
user1002358 Avatar asked Oct 19 '11 05:10

user1002358


People also ask

How do you change the value of a column based on another column in SQL?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.

How do you update data from the same table?

Update With Select Sub Query: Same Table. Thus, the simplest and straightforward way to update values from one table to another table is to use the UPDATE FROM SELECT statement. By using UPDATE FROM, you can avoid the complicated ways like cursors, table data type, temp table, etc.


1 Answers

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

update your_table set B = A where B is null 
like image 175
mu is too short Avatar answered Sep 24 '22 21:09

mu is too short