|
| 1 | +\c pg_features_demo |
| 2 | +SET ROLE TO demorole; |
| 3 | + |
| 4 | +/* |
| 5 | +
|
| 6 | +When it can be already foreseen that a table will grow huge (100+ GB) or there is for example a "hot data" / "cold data" |
| 7 | +scenario, then it makes sense to think about splitting up the table to so called partitions. And the good thing is that |
| 8 | +starting from v10 there is native support for that - so that users can continue to work with the "main" or "top level" |
| 9 | +table and not care or know about the sub-partitions where data rows are actually living in. |
| 10 | +
|
| 11 | +Different partitioning models available: |
| 12 | +
|
| 13 | +1) Range based - typically used for having yearly / monthly / weekly partitions. |
| 14 | +2) List based - to explicitly "tell" that rows with specific column(s) values need to go to a specific table |
| 15 | +3) Hash based - for cases where you need X sub-tables evenly filled, but Postgres can choose the exact distribution |
| 16 | +
|
| 17 | +
|
| 18 | +NB! As of Postgres v12 support for partitioning is almost complete - only automatic creation of sub-partitions and some |
| 19 | +primary key limitations remain, but previous versions had some more limitations so it's recommended to read through the |
| 20 | +documentation before taking them into use on pre v12. |
| 21 | +
|
| 22 | +*/ |
| 23 | + |
| 24 | +-- the "main" or "parent" table that users will be interacting with |
| 25 | +CREATE TABLE orders ( |
| 26 | + order_nr int8 NOT NULL , |
| 27 | + order_date timestamptz NOT NULL DEFAULT now() |
| 28 | + -- data columns ... |
| 29 | +) PARTITION BY RANGE (order_date); |
| 30 | + |
| 31 | +-- partition to hold data for year 2019 |
| 32 | +CREATE TABLE orders_y2019 PARTITION OF orders FOR VALUES FROM ('2019-01-01') TO ('2020-01-01'); |
| 33 | + |
| 34 | +-- we keep working with the "main" table ... |
| 35 | +INSERT INTO orders |
| 36 | + SELECT 1; |
| 37 | + |
| 38 | +SELECT * FROM orders; -- 1 row |
| 39 | + |
| 40 | +-- if you want to disable implicit scanning of sub-tables one can use the ONLY keyword |
| 41 | +SELECT * FROM ONLY orders; -- 0 rows |
| 42 | + |
| 43 | +/* |
| 44 | +
|
| 45 | +NB! Partition hierarchies can be built many levels deep if needed and mixing different partitioning models - to see the |
| 46 | +whole "tree" one can use the pg_partition_tree() function or for direct descendants of a table use the "psql" \d+ helper |
| 47 | +
|
| 48 | +*/ |
0 commit comments