170

I have two tables...

table1 ( id, item, price ) values:

id | item | price
-------------
10 | book | 20  
20 | copy | 30   
30 | pen  | 10

....table2 ( id, item, price) values:

id | item | price
-------------
10 | book | 20
20 | book | 30

Now I want to:

update table1 
   set table1.Price = table2.price 
 where table1.id = table2.id
   and table1.item = table2.item.

How do I do it?

2
  • 1
    @mrp: you shouldn't put every RDBM as tag because, someone might advice you some vendor specific solution. Commented Nov 17, 2009 at 2:02
  • 1
    For PostgreSQL, see SO answer Commented May 31, 2022 at 22:03

2 Answers 2

334

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
Sign up to request clarification or add additional context in comments.

9 Comments

It gives me error message: invalid object table1.
It gives me error The multi-part identifier "table1.price" could not be bound.
@Sam, that is because you are referencing table1 in the UPDATE and FROM clauses (the same table is referenced twice). According to the script you are actually updating the field in the table you are querying rather than the one you are updating. The SET clause should reference the UPDATE table i.e. UPDATE table1 SET price = b.price FROM (SELECT id, price AS p FROM table1) a INNER JOIN table2 b on a.id = b.id
it's not working in mysql
For mysql: UPDATE table1 INNER JOIN table2 ON table1.id = table2.id SET table1.Price = table2.price can be used
|
101

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

4 Comments

But this is updating more no of rows :( than it is...
It should update only the no of rows returned within the inner query, but doubled the no of update is happening :(
Updating double...
This should be the accepted answer because most of the DBs support subqueries, instead of joins, for an UPDATE statement. @niceApp

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.