Partitioning
Data Partitioning
Logically divides large data. Range, hash, and list methods.
Data Partitioning
Logically divides large data. Range, hash, and list methods.
Partitioning is a database technique that divides a large table or index into multiple smaller units based on logical criteria and stores them that way. Managing hundreds of millions of rows or more in a single table causes problems such as degraded query performance, index bloat, and increased management complexity, and partitioning can resolve these problems. Logically it is one table, but physically it is stored as multiple partitions, so it can be accessed transparently.
Range Partitioning divides data based on ranges of continuous values such as dates and numbers. It is suitable for time-series data; for example, if you create partitions by month, queries over a specific period scan only the relevant partitions, greatly improving performance. Hash Partitioning distributes data evenly based on the hash value of a specific column, and is effective when the data distribution is irregular. List Partitioning divides data based on a list of specific values, and is used for explicit groupings such as region codes or status values.
Composite Partitioning combines two or more partitioning methods. For example, Range-Hash first creates range partitions by date, and then creates subpartitions by hash within each partition. This provides the advantages of both time-based queries and even distribution. Also, Partition Pruning is an optimization technique that scans only the partitions matching the query conditions, and it is a core benefit of partitioning.
Partitioning and Sharding are often confused but are different concepts. Partitioning divides a table within a single database, while sharding distributes data across multiple database servers. Modern distributed databases (Vitess, CockroachDB, TiDB) combine the two concepts to provide horizontal scalability. Partitioning is an essential technique for efficiently storing and querying large training datasets in AI/ML workloads, and Hive-style partitioning is also widely used in data lakes.
-- ๋ถ๋ชจ ํ
์ด๋ธ ์์ฑ (ํํฐ์
์ ์)
CREATE TABLE orders (
id BIGSERIAL,
order_date DATE NOT NULL,
customer_id INTEGER,
amount DECIMAL(10, 2),
status VARCHAR(20)
) PARTITION BY RANGE (order_date);
-- ์๋ณ ํํฐ์
์์ฑ
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_customer ON orders (customer_id);
CREATE INDEX idx_orders_status ON orders (status);
-- ์ฟผ๋ฆฌ ์ ํํฐ์
ํ๋ฃจ๋ ํ์ธ
EXPLAIN ANALYZE
SELECT * FROM orders
WHERE order_date BETWEEN '2024-02-01' AND '2024-02-29';
-- orders_2024_02 ํํฐ์
๋ง ์ค์บ๋จ
-- ํํฐ์
๋ถ๋ฆฌ (์ค๋๋ ๋ฐ์ดํฐ ์์นด์ด๋ธ)
ALTER TABLE orders DETACH PARTITION orders_2024_01;
-- ๋
๋ฆฝ ํ
์ด๋ธ๋ก ๋ณํ๋์ด ์์นด์ด๋ธ ๊ฐ๋ฅ
-- ํด์ ํํฐ์
๋์ผ๋ก ๊ท ๋ฑ ๋ถ์ฐ
CREATE TABLE user_sessions (
session_id BIGINT NOT NULL,
user_id INT NOT NULL,
created_at DATETIME,
data JSON,
PRIMARY KEY (session_id, user_id)
)
PARTITION BY HASH(user_id)
PARTITIONS 8;
-- ๋ฆฌ์คํธ ํํฐ์
๋ (์ง์ญ๋ณ)
CREATE TABLE customers (
id INT NOT NULL,
name VARCHAR(100),
region VARCHAR(20),
PRIMARY KEY (id, region)
)
PARTITION BY LIST COLUMNS(region) (
PARTITION p_asia VALUES IN ('KR', 'JP', 'CN', 'TW'),
PARTITION p_europe VALUES IN ('DE', 'FR', 'UK', 'IT'),
PARTITION p_america VALUES IN ('US', 'CA', 'BR', 'MX'),
PARTITION p_others VALUES IN (DEFAULT)
);
-- Range-Hash ๋ณตํฉ ํํฐ์
๋
CREATE TABLE access_logs (
id BIGINT NOT NULL,
access_time DATETIME NOT NULL,
user_id INT,
endpoint VARCHAR(255),
PRIMARY KEY (id, access_time, user_id)
)
PARTITION BY RANGE (YEAR(access_time))
SUBPARTITION BY HASH(user_id)
SUBPARTITIONS 4 (
PARTITION p2023 VALUES LESS THAN (2024),
PARTITION p2024 VALUES LESS THAN (2025),
PARTITION p2025 VALUES LESS THAN (2026)
);
-- ํํฐ์
์ ๋ณด ์กฐํ
SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS, DATA_LENGTH
FROM INFORMATION_SCHEMA.PARTITIONS
WHERE TABLE_NAME = 'access_logs';
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, year, month
spark = SparkSession.builder \
.appName("DataPartitioning") \
.getOrCreate()
# ๋์ฉ๋ ๋ฐ์ดํฐ ๋ก๋
df = spark.read.parquet("s3://datalake/raw/events/")
# Hive ์คํ์ผ ํํฐ์
๋์ผ๋ก ์ ์ฅ
df.write \
.partitionBy("year", "month", "day") \
.mode("overwrite") \
.parquet("s3://datalake/partitioned/events/")
# ๊ฒฐ๊ณผ ๋๋ ํ ๋ฆฌ ๊ตฌ์กฐ:
# s3://datalake/partitioned/events/
# โโโ year=2024/
# โ โโโ month=01/
# โ โ โโโ day=01/
# โ โ โ โโโ part-00000.parquet
# โ โ โโโ day=02/
# โ โโโ month=02/
# โโโ year=2025/
# ํํฐ์
ํ๋ฃจ๋์ด ์ ์ฉ๋ ์ฝ๊ธฐ
df_january = spark.read.parquet("s3://datalake/partitioned/events/") \
.where(col("year") == 2024) \
.where(col("month") == 1)
# year=2024/month=01 ํํฐ์
๋ง ์ค์บ
# Dynamic Partition Overwrite
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
df_updates.write \
.partitionBy("year", "month") \
.mode("overwrite") \
.parquet("s3://datalake/partitioned/events/")
# ์
๋ฐ์ดํธ๋ ํํฐ์
๋ง ๋ฎ์ด์ฐ๊ธฐ
# Repartitioning (๋ฉ๋ชจ๋ฆฌ ๋ด ์ฌ๋ถํ )
df_balanced = df.repartition(100, col("customer_id"))
df_coalesced = df.coalesce(10) # ํํฐ์
์ ์ค์ด๊ธฐ
# Bucket์ ์ฌ์ฉํ ์กฐ์ธ ์ต์ ํ
df.write \
.bucketBy(32, "customer_id") \
.sortBy("order_date") \
.saveAsTable("orders_bucketed")
import psycopg2
from datetime import datetime, timedelta
def manage_partitions(conn, table_name: str, months_ahead: int = 3, months_retain: int = 24):
"""
ํํฐ์
์๋ ์์ฑ ๋ฐ ์ ๋ฆฌ
- ๋ฏธ๋ N๊ฐ์ ํํฐ์
๋ฏธ๋ฆฌ ์์ฑ
- ๋ณด๊ด ๊ธฐ๊ฐ ์ด๊ณผ ํํฐ์
๋ถ๋ฆฌ/์ญ์
"""
cursor = conn.cursor()
today = datetime.now()
# ๋ฏธ๋ ํํฐ์
์์ฑ
for i in range(months_ahead):
target_date = today + timedelta(days=30 * i)
partition_name = f"{table_name}_{target_date.strftime('%Y_%m')}"
start_date = target_date.replace(day=1)
end_date = (start_date + timedelta(days=32)).replace(day=1)
create_sql = f"""
CREATE TABLE IF NOT EXISTS {partition_name}
PARTITION OF {table_name}
FOR VALUES FROM ('{start_date.strftime('%Y-%m-%d')}')
TO ('{end_date.strftime('%Y-%m-%d')}');
"""
try:
cursor.execute(create_sql)
print(f"Created partition: {partition_name}")
except psycopg2.errors.DuplicateTable:
pass # ์ด๋ฏธ ์กด์ฌ
# ์ค๋๋ ํํฐ์
๋ถ๋ฆฌ
cutoff_date = today - timedelta(days=30 * months_retain)
cursor.execute(f"""
SELECT schemaname, tablename
FROM pg_tables
WHERE tablename LIKE '{table_name}_%'
""")
for schema, partition in cursor.fetchall():
try:
partition_date = datetime.strptime(
partition.replace(f"{table_name}_", ""),
"%Y_%m"
)
if partition_date < cutoff_date:
cursor.execute(f"ALTER TABLE {table_name} DETACH PARTITION {partition}")
cursor.execute(f"DROP TABLE {partition}")
print(f"Dropped old partition: {partition}")
except ValueError:
continue
conn.commit()
# ๋งค์ผ ์คํํ์ฌ ํํฐ์
๊ด๋ฆฌ
if __name__ == "__main__":
conn = psycopg2.connect("postgresql://localhost/mydb")
manage_partitions(conn, "orders", months_ahead=3, months_retain=24)
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
The partition key should be included in most query conditions. Querying without the partition key scans all partitions, which can actually degrade performance. Also, the partition key is difficult to change, so it must be chosen carefully.
Too many partitions (thousands or more) increase metadata management overhead and lengthen query planning time. Choose an appropriate unit (monthly, weekly, etc.) so that each partition contains enough data.
In PostgreSQL, partitioned tables have limitations in foreign key constraint support. When joining across partitions, if the partition key is included in the join key, it is optimized with a Partition-Wise Join; otherwise, performance may degrade.