Skip to content
Advertisement

Update with a subquery and a join

How do I update table1 with results of this query –

select b.description from 
table1 c
join 
(
    SELECT distinct a.hcpc, a.description
    FROM table2 a 
) b 
on b.hcpc = c.hcpc
where c.description = '0'

I want to do something like this –

update table1 
set table1.description = (select b.description from table1 c
join 
(
    SELECT distinct a.hcpc, a.description
    FROM table2 a 
) b 
on b.hcpc = c.hcpc
where c.description = '0'
) 

Advertisement

Answer

This question has been answered many times in SO… anyway, the query should be built this way

One option

update table1 c
set description = b.description
from
  (
    SELECT distinct a.hcpc, a.description
    FROM table2 a 
  ) b  
where b.hcpc = c.hcpc
  and c.description = '0'

Other option

with t as (
  SELECT distinct a.hcpc, a.description
  FROM table2 a
)
update table1 c
set description = t.description
from t
where t.hcpc = c.hcpc
  and c.description = '0'

Surely there are other additional ways…

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement