Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.92) (envelope-from ) id 1j6xLh-0007Ab-Ki for pgsql-general@arkaria.postgresql.org; Wed, 26 Feb 2020 14:07:41 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1j6xLg-0002f6-3V for pgsql-general@arkaria.postgresql.org; Wed, 26 Feb 2020 14:07:40 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j6xLf-0002ev-MB for pgsql-general@lists.postgresql.org; Wed, 26 Feb 2020 14:07:39 +0000 Received: from relay8-d.mail.gandi.net ([217.70.183.201]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1j6xLc-0006Ta-Ea for pgsql-general@postgresql.org; Wed, 26 Feb 2020 14:07:38 +0000 X-Originating-IP: 185.94.189.190 Received: from [10.8.8.15] (unknown [185.94.189.190]) (Authenticated sender: vik@postgresfriends.org) by relay8-d.mail.gandi.net (Postfix) with ESMTPSA id 948B51BF207; Wed, 26 Feb 2020 14:07:32 +0000 (UTC) Subject: Re: Invoice increment From: Vik Fearing To: =?UTF-8?Q?S=c3=b8ren_Frisk?= , pgsql-general@postgresql.org References: Message-ID: <5c11552a-615a-4cac-c886-7910d421bd4b@postgresfriends.org> Date: Wed, 26 Feb 2020 15:07:31 +0100 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.4.1 MIME-Version: 1.0 In-Reply-To: Content-Type: text/plain; charset=utf-8 Content-Language: en-US Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk 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