Skip to content
This repository was archived by the owner on Oct 11, 2024. It is now read-only.

Commit 561cdfb

Browse files
committedAug 14, 2019
Add "table partitioning" chapter
1 parent 4f92218 commit 561cdfb

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
 

‎07_table_partitioning.sql

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
*/
File renamed without changes.

0 commit comments

Comments
 (0)
This repository has been archived.