Here is a table of phone numbers named phone_number
:
phone_number | country_code | owner |
---|---|---|
07911 123456 | 44 | Ada |
08912 654321 | 44 | Thomas |
06 12 34 56 78 | 33 | Jonathan |
06 87 65 43 21 | 33 | Arthur |
Let’s say we want to partition this table by country code, therefore creating this table phone_number_bis
CREATE TABLE phone_number_bis (
phone_number VARCHAR,
country_code INTEGER,
owner VARCHAR NOT NULL,
PRIMARY KEY (phone_number, country_code)
) PARTITION BY LIST(country_code)
Loading the content of phone_number
into phone_number_bis
will produce the following error:
INSERT INTO phone_number_bis( phone_number, country_code, owner)
SELECT phone_number, country_code, owner
FROM phone_number;
ERROR: no partition of relation "phone_number_bis" found for row
Partition key of the failing row contains (country_code) = (44)
Is there a SQL command that could create all necessary partitions before loading data into phone_number_bis
, not knowing the content of the country_code
column in advance ?
NB: as Franck Heikens pointed out, partitioning the table may not be relevant for storing phone numbers. This is an example made in order to make a complex problem more understable.
3
Answers
As Laurenz Albe and jjanes said, it cannot be done only with a SQL command.
A PL/pgSQL procedure seems to be required here :
If your client is
psql
, you can usegexec
to make it run a query and then run each result as a new command. So then you would need to write one query which output a text string containing a suitable CREATE TABLE statement for each distinct country_code. To do it entirely on the server side, you could use pl/pgsql to do much the same thing, constructing a string and then using dynamic sql to EXECUTE the string.now split the partition from default partition create an new partition for values in 200 to 300.
https://www.postgresql.org/docs/current/ddl-partitioning.html
Quote:
Quote:
More partition, will consume more memory, there is an case: https://www.postgresql.org/message-id/flat/PH0PR11MB5191F459DCB44A91682FE8C8D6409%40PH0PR11MB5191.namprd11.prod.outlook.com#86aaad1ddd6350efc062c2dd79a31821