Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE based on if value exist in another table

I have two tables

Table A

Number
111       
222       
333       
444       

Table B

Number    Another
111       AAA
222       BBB
666       CCC
777       DDD

What I am would like to do, is apply an UPDATE statement conditional on whether the "Number" value in Table B exist in Table A. So the table would end up looking something like this.

Number    Another
111       ZZZ
222       ZZZ
666       CCC
777       DDD

I know I need to use an UPDATE query and probably some kind of JOIN, but I am not sure on the syntax.

Any help greatly appreciated.

like image 922
user3580480 Avatar asked Mar 04 '17 09:03

user3580480


People also ask

How can I update data from one table to another table?

We can update the table using UPDATE statement in SQL. The update statement is always followed by the SET command. The SET command is used to specify which columns and values need to be updated in a table.

Can we use exists in update in SQL?

The SQL Server (Transact-SQL) EXISTS condition is used in combination with a subquery and is considered to be met if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

How do you update a column based on another column?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.


2 Answers

Yes. You need to update using a join like this:

update t2
set t2.Another = 'ZZZ'
from table1 t1
join table2 t2 on t1.Number = t2.Number
like image 192
Gurwinder Singh Avatar answered Sep 30 '22 16:09

Gurwinder Singh


You can use exists also.

Query

update t1
set t1.[Another] = 'ZZZ'
from [TableB] t1
where exists(
    select 1 from [TableA] t2
    where t1.[Number] = t2.[Number]
);
like image 20
Ullas Avatar answered Sep 30 '22 17:09

Ullas