0

I have a 2 table like this:

table1: (time, value, id) , table2:(time, value, id, ...)

I need to update table1 with a result of a query on table2 based on id, for example the query can be:

SELECT * from table2 where value > 2

and this query returns more than hundreds of rows,

I need update table1 with these rows based on id (set time=q.time, value=q.value where id=q.id) is it possible with sql query?

I don't need UPSERT as I'm sure I have same id in both tables, just need update

1
  • please provide sample data and desired output Commented Apr 16, 2021 at 18:46

2 Answers 2

4

Postgres supports a FROM clause for UPDATE:

update table1
   set time = q.time, 
       value = q.value
from table2 q
where table2.id = table1.id
  and table2.value > 2;
Sign up to request clarification or add additional context in comments.

1 Comment

simple and precise.
0
SELECT * 
into temp buffer     
from table2 
where value > 2;


insert into table1(list of columns to be updated)
select (list of columns to be selected)
from buffer;

NOTE___ --buffer is a temporary table that stores the output of the main query -- make sure both tables (table1 and table2) have the same columns and are arranged in the same order

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.