Re: Combining INSERT with DELETE RETURNING

From: Thomas Kellerer <spam_eater(at)gmx(dot)net>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Combining INSERT with DELETE RETURNING
Date: 2017-03-24 15:30:35
Message-ID: ob3e2n$ue5$1@blaine.gmane.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alexander Farber schrieb am 24.03.2017 um 16:06:

> the doc https://www.postgresql.org/docs/9.6/static/sql-delete.html states:
>
> "The syntax of the RETURNING list is identical to that of the output list of SELECT."
>
> So I am trying to rewrite the INSERT .. ON CONFLICT DO NOTHING followed by a DELETE:
> into a single statement:
>
> INSERT INTO words_reviews (
> uid,
> author,
> nice,
> review,
> updated
> ) VALUES (
> DELETE FROM words_reviews
> WHERE author <> out_uid
> AND author = ANY(_uids)
> RETURNING
> uid,
> out_uid, -- change to out_uid
> nice,
> review,
> updated
> )
> ON CONFLICT DO NOTHING;

You need a CTE:

with deleted as (
DELETE FROM words_reviews
WHERE author <> out_uid
AND author = ANY(_uids)
RETURNING
uid,
out_uid, -- change to out_uid
nice,
review,
updated
)
INSERT INTO words_reviews (uid, author, nice, review, updated)
select *
from deleted
ON CONFLICT DO NOTHING;

In response to

Browse pgsql-general by date

  From Date Subject
Next Message DrakoRod 2017-03-24 15:57:08 Re: The same query is too slow in some time of execution
Previous Message David G. Johnston 2017-03-24 15:19:33 Re: Combining INSERT with DELETE RETURNING