0

I have the following simple SQL update:

update t2 set col = 2 
from t2, t1
where t2.id = t1.id
    and t1.name = 'test';

But all the rows in t2 are updated! i.e. not just the one with the id where name is 'test', how do I achieve this in Postgres?

2
  • 1
    "where t1.id = t1.id" Is that a typo? Commented Jan 4, 2015 at 4:39
  • oops, yes thanks fixed, still same problem Commented Jan 4, 2015 at 4:40

2 Answers 2

2

You've got too much from from t1,t2 do this:

update t2 set col = 2 
from t1
where t2.id = t1.id
    and t1.name = 'test';

If you must have t2 in the from alias it and join all three tables in the where..

update t2 as t2_up set col = 2 
from t2 as t2_from , t1
where t2_from.id = t1.id
    and t2_up.id = t2_from.id
    and t1.name = 'test';
Sign up to request clarification or add additional context in comments.

3 Comments

Cannot believe I have got so far in life without knowing this! I guess from <table updating> is implied already so not needed again in from like with a select?
yes, the the table after update is implied.and the the row values are auomatically available in the where clause.
@markmnl: From the manual: "Note that the target table must not appear in the from_list, unless you intend a self-join (in which case it must appear with an alias in the from_list)."
1

I'm guessing that you really mean:

update t2
    set col = 2 
from t2 join
     t1
     on t1.id = t2.id
where t1.name = 'test';

The condition t1.id = t1.id doesn't really make much sense in a query. It is equivalent to t1.id is not null. Hence, all rows in t2 would get updated due to the cross join.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.