pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Vik Fearing <vik@postgresfriends.org>
To: Søren Frisk <soeren.frisk@gmail.com>
To: pgsql-general@postgresql.org
Subject: Re: Invoice increment
Date: Wed, 26 Feb 2020 15:07:31 +0100
Message-ID: <5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org> (raw)
In-Reply-To: <dba07b2f-7c81-a522-f03f-9f46e6127b78@postgresfriends.org>
References: <CACe3Kr6jhD4BKv74bs7f3K6FDq7KM_QvCy3s35Dm8gfi5By9Xg@mail.gmail.com>
	<dba07b2f-7c81-a522-f03f-9f46e6127b78@postgresfriends.org>

On 26/02/2020 10:27, Vik Fearing wrote:
> WITH
> u (invoice_number) AS (
>     UPDATE invoice_numbers
>     SET invoice_number = invoice_number + 1
>     WHERE country = $1
>     RETURNING invoice_number
> ),
> i (invoice_number) AS (
>     INSERT INTO invoice_numbers (country, invoice_number)
>     SELECT $1, 1
>     WHERE NOT EXISTS (TABLE u)
>     ON CONFLICT (country) DO
>         UPDATE SET invoice_number = invoice_numbers.invoice_number + 1
>     RETURNING invoice_number
> )
> TABLE u UNION ALL TABLE i;

Actually this is probably some premature optimization that you don't
need.  Just the insert should be good enough.

INSERT INTO invoice_numbers (country, invoice_number)
VALUES ($1, 1)
ON CONFLICT (country) DO
    UPDATE SET invoice_number = invoice_numbers.invoice_number + 1
RETURNING invoice_number;

-- 
Vik Fearing





view thread (6+ messages)

Message-ID: <5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org>
Permalink:  ../5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org/
Also on:    postgresql.org/message-id/5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: vik@postgresfriends.org, soeren.frisk@gmail.com
  Subject: Re: Invoice increment
  In-Reply-To: <5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org>
  References: <CACe3Kr6jhD4BKv74bs7f3K6FDq7KM_QvCy3s35Dm8gfi5By9Xg@mail.gmail.com> <dba07b2f-7c81-a522-f03f-9f46e6127b78@postgresfriends.org> <5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox