Partition
Partition
A technique that logically divides large tables to improve query performance and management efficiency. Partition Pruning scans only the necessary partitions to optimize performance.
Partition
A technique that logically divides large tables to improve query performance and management efficiency. Partition Pruning scans only the necessary partitions to optimize performance.
Partitioning (Partition) is a technique that divides a large table into smaller pieces, either physically or logically. A single table is stored as multiple partitions, but the application uses it as if it were one table. Performance improves significantly through Partition Pruning, which scans only the necessary partitions according to the WHERE condition during a query.
Divides data by ranges of consecutive values. Suitable for date, time, and numeric data.
Divides data by lists of specific values. Suitable for classification based on discrete values.
Distributes data evenly using a hash function. Suitable for data without a specific pattern.
| Characteristics | Partition | Sharding |
|---|---|---|
| Split Location | Within a single DB instance | Multiple DB instances |
| Management Complexity | Managed automatically by the DB | Managed at the application level |
| Scalability | Limited by vertical scaling | Horizontal scaling possible |
| Transaction | ACID across the entire table | Distributed transactions required |
| Use Cases | Scale where a single DB is sufficient | Very large-scale data |
-- 부모 테이블 생성 (파티션 키 지정)
CREATE TABLE orders (
id SERIAL,
user_id INTEGER NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL,
created_at TIMESTAMP NOT NULL,
PRIMARY KEY (id, created_at) -- 파티션 키 포함 필수
) PARTITION BY RANGE (created_at);
-- 월별 파티션 생성
CREATE TABLE orders_2024_01 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
CREATE TABLE orders_2024_02 PARTITION OF orders
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');
CREATE TABLE orders_2024_03 PARTITION OF orders
FOR VALUES FROM ('2024-03-01') TO ('2024-04-01');
-- 기본 파티션 (범위 밖 데이터)
CREATE TABLE orders_default PARTITION OF orders DEFAULT;
-- 인덱스 생성 (파티션별 자동 적용)
CREATE INDEX idx_orders_user_id ON orders (user_id);
CREATE INDEX idx_orders_status ON orders (status);
-- Partition Pruning 동작 확인
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE created_at >= '2024-02-01' AND created_at < '2024-03-01';
-- 결과: orders_2024_02만 스캔
-- 국가별 List Partition
CREATE TABLE customers (
id SERIAL,
name VARCHAR(100) NOT NULL,
country_code CHAR(2) NOT NULL,
email VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id, country_code)
) PARTITION BY LIST (country_code);
-- 국가별 파티션 생성
CREATE TABLE customers_kr PARTITION OF customers
FOR VALUES IN ('KR');
CREATE TABLE customers_asia PARTITION OF customers
FOR VALUES IN ('JP', 'CN', 'TW', 'SG');
CREATE TABLE customers_us PARTITION OF customers
FOR VALUES IN ('US', 'CA');
CREATE TABLE customers_eu PARTITION OF customers
FOR VALUES IN ('DE', 'FR', 'GB', 'IT', 'ES');
CREATE TABLE customers_other PARTITION OF customers DEFAULT;
-- 한국 고객만 조회 (자동 Pruning)
SELECT * FROM customers WHERE country_code = 'KR';
-- customers_kr 파티션만 스캔
-- 해시 기반 균등 분배
CREATE TABLE logs (
id BIGSERIAL,
user_id INTEGER NOT NULL,
action VARCHAR(50) NOT NULL,
payload JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id, user_id)
) PARTITION BY HASH (user_id);
-- 4개 파티션으로 균등 분배
CREATE TABLE logs_p0 PARTITION OF logs
FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE logs_p1 PARTITION OF logs
FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE logs_p2 PARTITION OF logs
FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE logs_p3 PARTITION OF logs
FOR VALUES WITH (MODULUS 4, REMAINDER 3);
-- 1. 새 파티션 미리 생성 (자동화 권장)
CREATE TABLE orders_2024_04 PARTITION OF orders
FOR VALUES FROM ('2024-04-01') TO ('2024-05-01');
-- 2. 오래된 파티션 분리 (DETACH)
ALTER TABLE orders DETACH PARTITION orders_2024_01;
-- 3. 분리된 테이블 아카이브 또는 삭제
-- 옵션 A: 아카이브 테이블로 이동
ALTER TABLE orders_2024_01 RENAME TO orders_archive_2024_01;
-- 옵션 B: 데이터 삭제 (전체 파티션 즉시 삭제)
DROP TABLE orders_2024_01;
-- Full Table Scan 없이 즉시 삭제 (DELETE보다 훨씬 빠름)
-- 파티션 목록 확인
SELECT
parent.relname AS parent_table,
child.relname AS partition_name,
pg_get_expr(child.relpartbound, child.oid) AS partition_expression
FROM pg_inherits
JOIN pg_class parent ON pg_inherits.inhparent = parent.oid
JOIN pg_class child ON pg_inherits.inhrelid = child.oid
WHERE parent.relname = 'orders';
-- MySQL 파티션 생성
CREATE TABLE orders (
id INT AUTO_INCREMENT,
user_id INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
created_at DATE NOT NULL,
PRIMARY KEY (id, created_at)
)
PARTITION BY RANGE (YEAR(created_at) * 100 + MONTH(created_at)) (
PARTITION p202401 VALUES LESS THAN (202402),
PARTITION p202402 VALUES LESS THAN (202403),
PARTITION p202403 VALUES LESS THAN (202404),
PARTITION p_max VALUES LESS THAN MAXVALUE
);
-- 파티션 추가
ALTER TABLE orders ADD PARTITION (
PARTITION p202404 VALUES LESS THAN (202405)
);
-- 파티션 삭제
ALTER TABLE orders DROP PARTITION p202401;
-- 파티션 정보 확인
SELECT
TABLE_NAME,
PARTITION_NAME,
PARTITION_EXPRESSION,
PARTITION_DESCRIPTION,
TABLE_ROWS
FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_NAME = 'orders';
The partition key must be included in Primary Key and Unique constraints. Define a composite key, such as PRIMARY KEY (id, created_at).
If the WHERE clause has no partition key condition, all partitions are scanned. Use EXPLAIN to check the number of partitions actually scanned. Conditions wrapped in a function (e.g., YEAR(created_at) = 2024) may prevent Pruning from working.
Too many partitions actually degrade performance. PostgreSQL can handle thousands of partitions, but design them in appropriate units (monthly, quarterly) to match actual access patterns.