Re: Returning empty on insert

From: David Rowley <david(dot)rowley(at)2ndquadrant(dot)com>
To: Winanjaya Amijoyo <winanjaya(dot)amijoyo(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Returning empty on insert
Date: 2019-05-16 09:25:28
Message-ID: CAKJS1f9Nzqn4LzBTSFAeFmQfJF5mxDUqhk-oP9=N9u92J4-7gw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, 16 May 2019 at 21:13, Winanjaya Amijoyo
<winanjaya(dot)amijoyo(at)gmail(dot)com> wrote:
> When record not found then insert and return pid value or if not found then update based on pid and again return its pid.

You could do something like:

WITH s AS (
SELECT pid FROM test WHERE area = 'test5'
), i AS (
INSERT INTO test (area)
SELECT 'test5'
WHERE NOT EXISTS (SELECT 1 FROM s)
RETURNING pid
)
UPDATE area
SET last_update = CURRENT_TIMESTAMP
WHERE pid = (SELECT pid FROM s UNION SELECT pid FROM i)
RETURNING pid;

but be warned, it's could all fall over as soon as you have concurrent
sessions running this at the same time. You could protect against
that by doing some advisory locking (
https://www.postgresql.org/docs/11/explicit-locking.html#ADVISORY-LOCKS
), or taking an access exclusive lock on "test".

--
David Rowley http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message nigel.andersen 2019-05-16 09:36:56 Upgrading 9.1.17 to which version?
Previous Message Winanjaya Amijoyo 2019-05-16 09:13:38 Re: Returning empty on insert