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?
https://www.postgresql.org/docs/9.5/static/sql-insert.html
The
SET
andWHERE
clauses inON 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 specialexcluded
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With