Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - UPDATE table where ID is in SELECT?

I have a table where I want to update all rows with the ID that exists in the select result.

My pseudo-code:

UPDATE mytable as t
   SET t.status = 'PM'
 WHERE t.ID EXISTS IN (select ID from ...)

I have managed to do the select statement, now I want to use the result of the select statement to update a table.

like image 557
dpp Avatar asked Jul 29 '11 03:07

dpp


People also ask

Can we use update with WHERE clause?

The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.

How do I update from a select in SQL Server?

UPDATE from SELECT: The MERGE statement The MERGE statement is used to manipulate (INSERT, UPDATE, DELETE) a target table by referencing a source table for the matched and unmatched rows. The MERGE statement can be very useful for synchronizing the table from any source table.

Can we write update statement in select query?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

How do I update conditionally in SQL?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.


2 Answers

If you remove the exists you have a valid query from what I can tell.

UPDATE mytable 
   SET status = 'PM'
 WHERE id IN (select ID from ...)

Works for me in MySql 5.5, not sure which database you're using.

like image 151
Jesus Ramos Avatar answered Oct 08 '22 05:10

Jesus Ramos


One cannot use substitution in the UPDATE statement. The original query should be good when you leave out the " as t" part and both "t.".

like image 29
user3388611 Avatar answered Oct 08 '22 05:10

user3388611