Search Postgresql Archives

Re: Invoice increment

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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





[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]

  Powered by Linux