Skip to content

Partitioning Internals ​

Partition Pruning Deep Dive ​

sql
-- PostgreSQL 18
-- Partition pruning: planner loại partition không cần quét
CREATE TABLE orders (
  id BIGINT,
  created_at DATE,
  customer_id INT
) PARTITION BY RANGE (created_at);

CREATE TABLE orders_2023 PARTITION OF orders FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE orders_2024 PARTITION OF orders FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');

INSERT INTO orders SELECT g, DATE '2023-01-01' + (g % 700), g % 100 FROM generate_series(1, 100000) g;
ANALYZE orders;

-- Truy vấn có pruning:
EXPLAIN (COSTS OFF)
SELECT * FROM orders WHERE created_at >= '2024-01-01';

-- Plan (đã chạy trên PostgreSQL 18):
-- Seq Scan on orders_2024 orders
--   Filter: (created_at >= '2024-01-01'::date)
-- ✓ Chỉ partition 2024 xuất hiện trong plan; orders_2023 đã bị loại lúc lập plan

When Pruning Fails ​

⚠️ GOTCHA: Partition pruning silently fails in many common scenarios, causing full table scans across ALL partitions! Always verify with EXPLAIN to ensure pruning works.

→ See also: Partitioning vs Indexes: Decision Framework for choosing between partitioning and indexes

sql
-- PostgreSQL 18, dùng bảng orders tạo ở mục "Partition Pruning Deep Dive" phía trên
-- 1. Giá trị chỉ biết lúc chạy (current_date, tham số $1): VẪN loại được partition,
--    nhưng ở executor startup (không phải lúc lập plan), hiện là "Subplans Removed"
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM orders WHERE created_at >= current_date - 1;
-- Append (actual rows=0.00 loops=1)
--   Subplans Removed: 2

-- 2. Hàm/biểu thức bọc cột khoá: KHÔNG loại được partition nào
EXPLAIN (COSTS OFF) SELECT * FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2024;
-- Append
--   -> Seq Scan on orders_2023 orders_1
--   -> Seq Scan on orders_2024 orders_2
-- (so với '2024'::TEXT thì không chạy: ERROR: operator does not exist: numeric = text)

-- 3. EXTRACT(MONTH FROM created_at) = 1 cũng vậy
-- Sửa: lọc bằng khoảng trực tiếp trên cột khoá
EXPLAIN (COSTS OFF)
SELECT * FROM orders WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01';
-- Seq Scan on orders_2024 orders

Range vs List vs Hash Partitioning ​

text
Chiến lược  Chọn khi                                   Bảo trì
────────────────────────────────────────────────────────────────────────
Range       Khoảng liên tục, nhất là thời gian         Tạo partition mới theo lịch; bỏ dữ liệu cũ bằng DETACH/DROP
List        Giá trị rời rạc (vùng, loại)               Thêm giá trị mới = thêm partition (hoặc DEFAULT)
Hash        Chia đều tải, không có khoá tự nhiên       Số MODULUS đổi rất khó; không bỏ theo thời gian;
                                                       pruning chỉ với điều kiện bằng (=)
sql
-- PostgreSQL 18
-- RANGE: hợp với dữ liệu thời gian (bỏ dữ liệu cũ dễ)
CREATE TABLE logs (
  id BIGINT,
  created_at TIMESTAMP,
  message TEXT
) PARTITION BY RANGE (created_at);

CREATE TABLE logs_2023_12 PARTITION OF logs FOR VALUES FROM ('2023-12-01') TO ('2024-01-01');
CREATE TABLE logs_2024_01 PARTITION OF logs FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');

-- Bỏ partition cũ: DETACH ... CONCURRENTLY (không khoá chặn truy vấn, không chạy trong khối giao dịch) rồi mới DROP.
-- DROP TABLE không hoàn tác: archive/backup partition trước khi xoá.
ALTER TABLE logs DETACH PARTITION logs_2023_12 CONCURRENTLY;
DROP TABLE logs_2023_12;

-- LIST: theo danh mục/vùng
CREATE TABLE orders_by_region (
  id BIGINT,
  region VARCHAR(20)
) PARTITION BY LIST (region);

CREATE TABLE orders_us PARTITION OF orders_by_region FOR VALUES IN ('USA', 'Canada');
CREATE TABLE orders_eu PARTITION OF orders_by_region FOR VALUES IN ('UK', 'France');

-- HASH: chia đều tải
CREATE TABLE events (
  user_id BIGINT
) PARTITION BY HASH (user_id);
-- Partition KHÔNG tự tạo: phải tạo đủ MODULUS phần
CREATE TABLE events_p0 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE events_p1 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE events_p2 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE events_p3 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 3);

Partition-wise Joins ​

sql
-- PostgreSQL 18
-- enable_partitionwise_join (PG 11+) MẶC ĐỊNH TẮT. Bật thì join được thực hiện theo từng cặp partition.
-- Điều kiện: hai bảng chia cùng cách (cùng kiểu khoá, cùng ranh giới) và điều kiện join gồm khoá phân vùng.
-- Đổi lại planning time và bộ nhớ tăng theo số partition.
CREATE TABLE pw_orders (id BIGINT, created_at DATE) PARTITION BY RANGE (created_at);
CREATE TABLE pw_orders_2023 PARTITION OF pw_orders FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE pw_orders_2024 PARTITION OF pw_orders FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
CREATE TABLE pw_shipments (id BIGINT, order_id BIGINT, created_at DATE) PARTITION BY RANGE (created_at);
CREATE TABLE pw_shipments_2023 PARTITION OF pw_shipments FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE pw_shipments_2024 PARTITION OF pw_shipments FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
INSERT INTO pw_orders SELECT g, DATE '2023-01-01' + (g % 700) FROM generate_series(1, 50000) g;
INSERT INTO pw_shipments SELECT g, g, DATE '2023-01-01' + (g % 700) FROM generate_series(1, 50000) g;
ANALYZE pw_orders;
ANALYZE pw_shipments;

SET enable_partitionwise_join = on;  -- theo phiên

EXPLAIN (COSTS OFF)
SELECT o.id, s.id
FROM pw_orders o
JOIN pw_shipments s ON o.id = s.order_id AND o.created_at = s.created_at;

-- Plan (đã chạy trên PostgreSQL 18; kiểu join do planner chọn theo dữ liệu):
-- Append
--   -> Hash Join (pw_shipments_2023 ⋈ pw_orders_2023)
--   -> Hash Join (pw_shipments_2024 ⋈ pw_orders_2024)
-- ✓ Mỗi cặp partition join riêng; tắt tham số thì plan là một Hash Join trên hai Append

Maintenance Operations ​

sql
-- PostgreSQL 18, dùng bảng orders ở mục "Partition Pruning Deep Dive"
CREATE INDEX ON orders (customer_id);  -- index trên bảng cha tự tạo ở mọi partition

-- DETACH: gỡ partition (dữ liệu còn nguyên).
-- Không có CONCURRENTLY thì khoá ACCESS EXCLUSIVE trên bảng cha (chặn mọi truy vấn); CONCURRENTLY không chạy trong transaction.
ALTER TABLE orders DETACH PARTITION orders_2023 CONCURRENTLY;
-- orders_2023 giờ là bảng độc lập

-- ATTACH: gắn lại (đúng ranh giới cũ). Quét bảng để kiểm tra dòng nằm trong khoảng;
-- thêm sẵn CHECK khớp khoảng thì bỏ qua lần quét này.
ALTER TABLE orders ATTACH PARTITION orders_2023
  FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');

-- REINDEX từng partition của bảng cha (PG14+ hỗ trợ trên bảng phân vùng)
REINDEX TABLE CONCURRENTLY orders;

-- Nạp dữ liệu rồi mới gắn: tạo bảng độc lập, nạp, thêm CHECK, ATTACH
CREATE TABLE orders_2025 (LIKE orders);
INSERT INTO orders_2025 VALUES (1, '2025-03-01', 7);
ALTER TABLE orders_2025 ADD CONSTRAINT orders_2025_range
  CHECK (created_at >= '2025-01-01' AND created_at < '2026-01-01');
ALTER TABLE orders ATTACH PARTITION orders_2025
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');

Common Pitfalls & Best Practices ​

sql
-- PostgreSQL 18
-- ❌ Hàm/ép kiểu bọc CỘT khoá làm mất pruning (ở đây cột là TIMESTAMP)
CREATE TABLE orders_ts (id BIGINT, created_at TIMESTAMP, customer_id INT) PARTITION BY RANGE (created_at);
CREATE TABLE orders_ts_2023 PARTITION OF orders_ts FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');
CREATE TABLE orders_ts_2024 PARTITION OF orders_ts FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
EXPLAIN (COSTS OFF) SELECT * FROM orders_ts WHERE created_at::DATE = '2024-01-01';
-- Append -> Seq Scan trên CẢ orders_ts_2023 và orders_ts_2024

-- ✓ Dùng khoảng trên chính cột khoá
EXPLAIN (COSTS OFF)
SELECT * FROM orders_ts
WHERE created_at >= '2024-01-01' AND created_at < '2024-01-02';
-- Seq Scan on orders_ts_2024 orders_ts

-- ❌ Quá nhiều partition: mỗi partition là một bảng thật (catalog, planning time, bộ nhớ);
--    chia theo user_id thành hàng triệu partition không dùng được.
-- ✓ Số partition theo retention và kích thước dữ liệu (thường vài chục đến vài trăm);
--    cỡ hàng nghìn thì đo planning time trước.
--    Khoá phân vùng có thể là biểu thức, vd PARTITION BY RANGE (date_trunc('month', created_at)),
--    nhưng truy vấn phải lọc đúng biểu thức đó mới prune.

-- ❌ Ép kiểu cột khoá: WHERE created_at::TEXT >= '2024-01-01' không prune được (ép kiểu cột khoá phân vùng).
-- ✓ Ép kiểu HẰNG thì vẫn prune (hằng được tính trước khi lập plan):
EXPLAIN (COSTS OFF) SELECT * FROM orders WHERE created_at = '2024-01-01'::DATE;
-- Seq Scan on orders_2024 orders

Phải nhớ

  • Luôn kiểm pruning bằng EXPLAIN: lọc trực tiếp trên cột khoá phân vùng, không bọc hàm/ép kiểu cột. Giá trị chỉ biết lúc chạy vẫn prune (thấy "Subplans Removed").
  • Khoá chính/UNIQUE trên bảng phân vùng phải chứa mọi cột khoá phân vùng (MySQL cũng vậy, và MySQL không cho foreign key trên bảng phân vùng).
  • Gỡ partition cũ bằng DETACH PARTITION ... CONCURRENTLY (ngoài transaction) rồi mới DROP; DROP không hoàn tác.