Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres upsert using results from select

I'm trying to upsert with postgres using values from a select. It looks like:

INSERT INTO foo (a, b, c)
SELECT a_, b_, c_
-- hairy sql
ON CONFLICT (...condition...) DO UPDATE
SET "c"=???

On conflict, I want to use one of the values from my select statement, but I can't find the right syntax to alias it. How can I do this with Postgres?

like image 416
RYS Avatar asked Jun 09 '17 20:06

RYS


1 Answers

Use the excluded keyword:

INSERT INTO foo (a, b, c)
SELECT a_, b_, c_
-- hairy sql
ON CONFLICT (...condition...) DO UPDATE
  SET c = excluded.c;
like image 114
a_horse_with_no_name Avatar answered Nov 04 '22 05:11

a_horse_with_no_name