Table1 columns: id, name
Table2 columns: id, status.
How to make request that update Table1.name for Table1.id = 'some_id' if Table2.id = Table1.id and Table2.status = 'some_status' ?
Thanks in advance.
Table1 columns: id, name
Table2 columns: id, status.
How to make request that update Table1.name for Table1.id = 'some_id' if Table2.id = Table1.id and Table2.status = 'some_status' ?
Thanks in advance.
update Table1 set Table1.name = 'XXX'
where Table1.id = 'some_id'
and exists (select 1 from Table2 where Table2.id = Table1.id and Table2.status = 'some_status');
The EXISTS keyword tests for the existence of any rows in a subquery. If no rows are found, the answer is FALSE. Otherwise, the subquery returns TRUE. NOT EXISTS reverses the results.
Note that the entire subquery is executed, even though EXISTS need only know whether or not the subquery returns any rows — so beware using EXISTS with subqueries that return large numbers of rows.
It’s worth noting that this sort of query is sometimes referred to as a “semijoin”. A semijoin is a SELECT statement that uses the EXISTS keyword to compare rows in a table with rows in another table.
In addition to that it's a correlated query which is executing for each row of Table1.
EXISTS may replace IN in many cases and often is more beneficial than IN.
try something like this
update table1
set table1.name = 'newName'
FROM table1 inner join table2 on table1.id = table2.id
where table2.status = 1enter code here