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 1j6syY-0006eI-VB for pgsql-general@arkaria.postgresql.org; Wed, 26 Feb 2020 09:27:31 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1j6syX-0002nh-Ib for pgsql-general@arkaria.postgresql.org; Wed, 26 Feb 2020 09:27:29 +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 1j6syX-0002jA-58 for pgsql-general@lists.postgresql.org; Wed, 26 Feb 2020 09:27:29 +0000 Received: from relay9-d.mail.gandi.net ([217.70.183.199]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1j6syU-00042v-IY for pgsql-general@postgresql.org; Wed, 26 Feb 2020 09:27:27 +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 relay9-d.mail.gandi.net (Postfix) with ESMTPSA id DAE11FF811; Wed, 26 Feb 2020 09:27:22 +0000 (UTC) Subject: Re: Invoice increment To: =?UTF-8?Q?S=c3=b8ren_Frisk?= , pgsql-general@postgresql.org References: From: Vik Fearing Message-ID: Date: Wed, 26 Feb 2020 10:27:21 +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: 8bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk On 26/02/2020 09:38, Søren Frisk wrote: > Hi all > > I'm trying to find a way to increment an invoice number. And i think it > would be pretty straight forward just using a SERIAL int. But as we're > selling across multiple countries, i need the invoice increment to be reset > by a country_id. any good way to achieve this in a dynamic way? A serial column is absolutely not a good fit for invoice numbers because in some (most? all?) countries, the numbers are not allowed to have gaps. The way I would do it is have an invoice_numbers table like this: CREATE TABLE invoice_numbers ( country text PRIMARY KEY REFERENCES countries, invoice_number bigint NOT NULL ); And then you can get the next number with something like this: 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; You can just put that in an SQL function for convenience. > Hope this is the right place to ask. Yes, it is. -- Vik Fearing