postgresql: INSERT INTO table_A (col_b) SELECT col_d from table_B WHERE table_B.col_c = table_A.col_a

Viewed 23

I have 2 tables. Table A :

Col_a | Col_b
--------------
abc   | [null]
def   | [null]

Table B :

Col_c | Col_d
-------------
abc   | 123
def   | 456

How can I insert Col_d from Table B to Col_b on Table A? Here's what I've tried :

INSERT INTO Table_A (Col_b) SELECT Col_d FROM Table_B
WHERE Col.c = (SELECT Col_a FROM Table_A);

The WHERE conditions doesn't seem can be used that way. Any idea?

1 Answers

I think you want update, not insert:

update tablea a
set col_b = b.col_d
from tableb b 
where b.col_a = a.col_c

For every row of tablea whose col_a can be found in tableb, this updates col_b to the value stored in col_d in tableb.

Related