Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is INSERT ON CONFLICT UPDATE from WITH query possible in postgresql 9.5?

I'm trying to insert (or update on conflict) rows from CTE but struggling to find right syntax for it. The table I'm inserting in looks like this (Simplified for the sake of clarity)

        Column        |           Type           |                            Modifiers
----------------------+--------------------------+------------------------------------------------------------------
 id                   | integer                  | not null default nextval('"QuestionStatistic_id_seq"'::regclass)
 questionId           | integer                  |
 count                | integer                  | not null default 0
Indexes:
    "QuestionStatistic_pkey" PRIMARY KEY, btree (id)
    "QuestionStatistic_questionId_key" UNIQUE CONSTRAINT, btree ("questionId")

This is my query:

with "Statistic" as (
   select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count") SELECT "questionId", "count" FROM "Statistics" 
ON CONFLICT ("questionId") DO UPDATE SET "count" = "Statistics"."count"

which gives me ERROR: missing FROM-clause entry for table "Statistics" on SET "count" = "Statistics"."count" part. I also tried to add FROM to update clause but got ERROR: syntax error at or near "FROM". Is there a way to make INSERT ON CONFLICT UPDATE work with CTE?

like image 501
fourslashw Avatar asked Jan 29 '23 01:01

fourslashw


1 Answers

https://www.postgresql.org/docs/9.5/static/sql-insert.html

The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the special excluded table.

thus try:

with "Statistic" as (
   select "questionId", "count" from "SomeTable"
)
INSERT INTO "QuestionStatistic" ("questionId", "count")
SELECT "questionId", "count" FROM "Statistics" 
ON CONFLICT ("questionId") DO UPDATE 
SET "count" = excluded."count"
like image 143
Vao Tsun Avatar answered Jan 31 '23 22:01

Vao Tsun