분산을 위한 해시 파티셔닝
파티션 전체에 데이터를 고르게 분산하도록 해시 파티셔닝을 구현합니다. 특정 파티션에 부하가 집중되는 현상을 방지하는 데 유용합니다.
분산을 위한 해시 파티셔닝은(는) CoddyKit의 무료 Advanced PostgreSQL: Indexing, Partitioning, Replication 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Advanced PostgreSQL: Indexing, Partitioning, Replication 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Advanced PostgreSQL: Indexing, Partitioning, Replication 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Hash Partitioning?
Welcome to Hash Partitioning! This strategy helps distribute data evenly across multiple partitions. Instead of dividing data by ranges or specific values, it uses a hash function.
This approach is especially useful when you want to avoid 'hot spots' where one partition receives significantly more data or queries than others.
Why Use Hash Partitioning?
Hash partitioning is ideal for:
- Even Distribution: It spreads data uniformly across partitions, preventing any single partition from becoming too large or slow.
- Avoiding Hot Spots: Useful when your partition key doesn't have a natural order or predictable distribution (unlike time-series data for Range Partitioning).
- Improved Concurrency: Queries can often operate on different partitions in parallel, boosting performance.
Hash Partitioning Syntax
To use hash partitioning, you define a parent table with PARTITION BY HASH (column_name). Then, you create child partitions using FOR VALUES WITH (MODULUS n, REMAINDER r).
- MODULUS (n): The total number of partitions you plan to have.
- REMAINDER (r): A unique number from 0 to n-1, indicating which 'bucket' of hashed values this partition will hold.
Creating a Hash-Partitioned Table
Let's create a table for user activity logs, partitioned by a user_id. We'll start with a parent table and two partitions. Note how the REMAINDER values cover the MODULUS.
CREATE TABLE user_activity (
activity_id SERIAL,
user_id INT NOT NULL,
activity_type VARCHAR(50),
activity_time TIMESTAMP DEFAULT NOW()
) PARTITION BY HASH (user_id);
CREATE TABLE user_activity_0
PARTITION OF user_activity
FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE TABLE user_activity_1
PARTITION OF user_activity
FOR VALUES WITH (MODULUS 2, REMAINDER 1);How Data is Distributed
When you insert data, PostgreSQL calculates a hash value for the user_id. It then performs a modulo operation (hash_value % MODULUS). The result determines which partition the row belongs to.
For example, if MODULUS is 2:
- If
hash_value % 2 = 0, it goes touser_activity_0. - If
hash_value % 2 = 1, it goes touser_activity_1.
Inserting Data Example
Let's insert some data into our user_activity table. PostgreSQL automatically directs each row to the correct hash partition based on the user_id.
Try inserting different user_id values and observe the distribution!
INSERT INTO user_activity (user_id, activity_type) VALUES
(101, 'login'),
(202, 'logout'),
(303, 'view_item'),
(404, 'add_to_cart'),
(101, 'browse_category'),
(505, 'purchase');
SELECT tableoid::regclass as partition_name, *
FROM user_activity
ORDER BY user_id;Querying Hash Partitions
Querying a hash-partitioned table is just like querying a regular table. PostgreSQL's query planner is smart enough to use partition pruning.
If your query includes the partition key (e.g., WHERE user_id = 101), the planner will only scan the relevant partition, significantly speeding up queries.
SELECT * FROM user_activity WHERE user_id = 101;
-- To see pruning in action:
EXPLAIN SELECT * FROM user_activity WHERE user_id = 101;Hash vs. Other Partition Types
Unlike Range partitioning (based on intervals) or List partitioning (based on specific values), Hash partitioning doesn't group data logically.
Its strength is in spreading data evenly, making it great for keys without natural ranges (like UUIDs or arbitrary IDs) and for preventing specific parts of your data from becoming bottlenecks.
Considerations & Maintenance
When using hash partitioning:
- Choose your key wisely: The partition key should have a good distribution of hash values.
- Modulus & Remainder: Ensure all
REMAINDERvalues from 0 toMODULUS - 1are covered by partitions. - Adding/Removing Partitions: Changing the
MODULUSlater requires re-hashing all data, which can be complex. Plan your partition count carefully.
Hash Partitioning Quiz
Which scenario is best suited for PostgreSQL hash partitioning?
Hash Partitioning Recap
In this lesson, you've learned about PostgreSQL hash partitioning:
- It distributes data evenly based on a hash function of the partition key.
- It uses
MODULUSandREMAINDERto define partitions. - It's excellent for avoiding hot spots and improving performance for non-sequential or arbitrary keys.
- Queries benefit from partition pruning when the partition key is used.
Hash partitioning is a powerful tool for scaling your database when even data spread is crucial.
자주 묻는 질문
“분산을 위한 해시 파티셔닝” 강의는 무료인가요?
네 — “분산을 위한 해시 파티셔닝” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Advanced PostgreSQL: Indexing, Partitioning, Replication 강의 전체를 잠금 해제할 수 있습니다. Advanced PostgreSQL: Indexing, Partitioning, Replication 강의에는 총 4개의 강의가 포함되어 있습니다.
“분산을 위한 해시 파티셔닝”에서 뭘 배우나요?
파티션 전체에 데이터를 고르게 분산하도록 해시 파티셔닝을 구현합니다. 특정 파티션에 부하가 집중되는 현상을 방지하는 데 유용합니다. 브라우저에서 직접 실행하는 실습 코드로 Advanced PostgreSQL: Indexing, Partitioning, Replication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Advanced PostgreSQL: Indexing, Partitioning, Replication을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Advanced PostgreSQL: Indexing, Partitioning, Replication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“분산을 위한 해시 파티셔닝” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Advanced PostgreSQL: Indexing, Partitioning, Replication 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Advanced PostgreSQL: Indexing, Partitioning, Replication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 분산을 위한 해시 파티셔닝
- 하위 파티셔닝 기법
- 파티션 테이블 관리
- 시간 기준 범위 파티셔닝