7

I have table called temp_table which consist of following rows:

 cola colb result
 ----------------
  p4   s1    0
  p8   s1    0
  p9   s1    0
  p5   f1    0
  p8   f1    0

Now I need to update result column with the count(*) of colb. For which i am trying the following query:

update tem_table
set result = x.result
from tem_table tt
inner join(select colb,count(*) as result from tem_table group by colb) x
on x.colb = tt.colb;

And selecting distinct colb and result from temp_table:

select distinct colb,result from tem_table;

Getting output:

colb result
-----------
 s1    3
 f1    3

But the expected output is:

colb result
-----------
 s1    3
 f1    2

I am not getting where I am getting wrong in my query? Please help me.Thanks

1 Answer 1

26

You should not repeat the table to be updated in the from clause. This will create a cartesian self join.

Quote 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)

(Emphasis mine)

Unfortunately UPDATE does not support explicit joins using the JOIN keyword. Something like this should work:

update tem_table
  set result = x.result
from (
    select colb,count(*) as result 
    from tem_table 
    group by colb
) x
where x.colb = tem_table.colb;
Sign up to request clarification or add additional context in comments.

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.