Analytical workloads typically require the analysis and computation of massive amounts of data, which places high demands on the query and data management capabilities of the database. OceanBase Database uses partitioning to horizontally split the data of a table into multiple data subsets by partition key, which improves query efficiency and data management:
- Improved query efficiency: Partition pruning reduces the scanning of irrelevant data.
- Data maintenance: Supports data management at partition granularity, such as data archiving and cleanup.
- Data distribution: Distributes data at partition granularity, which spreads data across multiple nodes and provides good scalability.
Role of partitions
In OceanBase Database, a partition is the basic unit of horizontal sharding and the smallest physical unit for data distribution, load balancing, and parallel operations. A large table is logically split into multiple smaller, more manageable independent blocks, and each partition (or even different replicas of a partition) can be stored on different OBServer nodes in the cluster.
This design brings fundamental advantages to analytical workloads: when the storage or computing capacity of a single node reaches its limit, you only need to add nodes and redistribute partitions to achieve near-linear horizontal scaling, easily handling PB-scale data.
Partition pruning improves query efficiency
After partitioning, when you query by the partition column, partition pruning can identify the partitions that meet the query conditions in some scenarios, so the query does not need to access the partitions that do not meet the conditions.
In the following example, hash partitions are created on column c2. For the query condition c2 = 1, partition pruning identifies that only partition p1 needs to be queried.
-- Create a table t1 with four hash partitions. The partition key is C2.
CREATE TABLE t1(c1 INT, c2 INT) PARTITION BY HASH(c2) PARTITIONS 4;
-- Query with c2 = 1 to prune to partition p1
EXPLAIN SELECT * FROM t1 WHERE c2 = 1;
The execution plan output is as follows:
+------------------------------------------------------------------------------------+
| Query Plan |
+------------------------------------------------------------------------------------+
| =============================================== |
| |ID|OPERATOR |NAME|EST.ROWS|EST.TIME(us)| |
| ----------------------------------------------- |
| |0 |TABLE FULL SCAN|t1 |1 |3 | |
| =============================================== |
| Outputs & filters: |
| ------------------------------------- |
| 0 - output([t1.c1], [t1.c2]), filter([t1.c2 = 1]), rowset=16 |
| access([t1.c2], [t1.c1]), partitions(p1) |
| is_index_back=false, is_global_index=false, filter_before_indexback[false], |
| range_key([t1.__pk_increment]), range(MIN ; MAX)always true |
+------------------------------------------------------------------------------------+
Partition pruning filters out unnecessary data, but too many partitions can also cause other problems, such as excessive metadata and reduced pruning efficiency. Therefore, for columnstore tables in OceanBase Database, we recommend that a single partition contain at least 1 million rows (100 W).
Partitions as data maintenance units
In database O&M, using partitions as the basic unit of data maintenance greatly simplifies daily management, for example, in data cleanup scenarios and partition-level statistics collection.
Take the data cleanup scenario as an example. After data is partitioned by time, cleaning up expired data no longer requires deleting rows one by one. Instead, you can delete the entire historical partition. This operation only modifies metadata and fully releases disk space, avoiding the performance overhead of traditional DML delete operations.
By naturally grouping data by partition key (such as time), maintenance operations change from "row-by-row scanning" to "batch processing", which greatly improves management efficiency and reduces O&M complexity.
Partitions as data distribution units
As the data distribution unit of OceanBase Database, a partition has replicas that can be placed on different OBServer nodes to scale storage and computing.
Storage scalability: When you create a partitioned table, OceanBase Database automatically schedules the partitions and their replicas to different physical nodes based on cluster resources. This means that the capacity of a single table is no longer limited by a single server's disk but by the storage capacity of the entire cluster. When the storage space of the cluster is insufficient, you can add nodes to scale out.
Parallel computing: This is one of the key factors for high performance in analytical workloads. When a query (especially a query that involves a full table scan or large-scale aggregation) is executed, the OceanBase Database optimizer identifies the partitions involved in the query. The query task can be decomposed into multiple subtasks and pushed down to the nodes where the data partitions reside for parallel execution. For example, a
SUM()operation calculates subtotals locally in each partition and then aggregates the intermediate results to obtain the final sum. This fully uses the computing power of multiple nodes and significantly accelerates the query.
Basic partitioning methods in OceanBase Database
OceanBase Database supports three basic partitioning methods: HASH/KEY, RANGE/RANGE COLUMNS, and LIST/LIST COLUMNS. Each method applies to different scenarios.
HASH/KEY partitioning
This method generally applies when the NDV (number of distinct values) of the partition column is large and clear ranges are difficult to define. Its advantage is that data without specific rules can be evenly distributed across partitions. Its disadvantage is that partition pruning is difficult for range queries.
Applicable scenarios:
- No clear query pattern, and data must be evenly distributed across multiple nodes (such as user IDs and transaction IDs).
Design considerations:
Partition key selection:
- The NDV (number of unique values) is much larger than the number of partitions (for example, the NDV of user IDs should be much larger than the number of partitions).
- Prefer integer or time columns with no skew or only slight skew (such as
user_id,order_time, or auto-increment columns). - Fields that are frequently used as query conditions (such as
user_idused as a join key).
Number of partitions:
- Make sure that the number of partitions matches the number of servers in the cluster to avoid unbalanced resource allocation.
Example scenario:
-- HASH partitioning, evenly distributed by user_id
CREATE TABLE customer (
user_id BIGINT NOT NULL,
login_time TIMESTAMP NOT NULL,
customer_name VARCHAR(100) NOT NULL,
phone_num BIGINT NOT NULL,
city_name VARCHAR(50) NOT NULL,
sex INT NOT NULL,
id_number VARCHAR(18) NOT NULL,
home_address VARCHAR(255) NOT NULL,
office_address VARCHAR(255) NOT NULL,
age INT NOT NULL
)
PARTITION BY HASH(user_id) PARTITIONS 128;
RANGE/RANGE COLUMNS partitioning
This method generally applies when the partition key can be easily divided into clear ranges. For example, a large table that records transaction details can be RANGE partitioned by the column that represents the time of the record.
Applicable scenarios:
- Data grows over time or numeric ranges (such as
order_timeandprice). - Historical data must be pruned quickly (such as querying only the data of the last month).
Design considerations:
Partition key selection:
- A time field (such as
order_time) or a continuous numeric field. - Partition boundaries must align with business query conditions (such as daily or monthly partitions).
- A time field (such as
Number of partitions:
- Set partitions based on data growth, for example, partition by month.
Example scenario:
-- Create a system log table that is RANGE partitioned by log time on a monthly basis, which supports fast queries and data archiving.
CREATE TABLE system_logs (
log_id BIGINT,
log_date TIMESTAMP NOT NULL,
log_level VARCHAR(10),
source_system VARCHAR(50),
user_id BIGINT,
log_message TEXT,
client_ip VARCHAR(15)
)
-- Primary partition: RANGE partitioned by month, with date values directly expressing partition boundaries.
PARTITION BY RANGE COLUMNS(log_date) (
PARTITION p_202001 VALUES LESS THAN ('2020-02-01'),
PARTITION p_202002 VALUES LESS THAN ('2020-03-01'),
PARTITION p_202003 VALUES LESS THAN ('2020-04-01'),
PARTITION p_202004 VALUES LESS THAN ('2020-05-01'),
PARTITION p_202005 VALUES LESS THAN ('2020-06-01'),
PARTITION p_202006 VALUES LESS THAN ('2020-07-01'),
PARTITION p_202007 VALUES LESS THAN ('2020-08-01'),
PARTITION p_202008 VALUES LESS THAN ('2020-09-01'),
PARTITION p_202009 VALUES LESS THAN ('2020-10-01'),
PARTITION p_202010 VALUES LESS THAN ('2020-11-01'),
PARTITION p_202011 VALUES LESS THAN ('2020-12-01'),
PARTITION p_202012 VALUES LESS THAN ('2021-01-01'),
-- The default partition handles records of future data or records with abnormal time formats.
PARTITION p_future VALUES LESS THAN (MAXVALUE)
);
LIST/LIST COLUMNS partitioning
This method generally applies when you need to explicitly control how each row is mapped to a specific partition. Its advantage is that unordered or unrelated data sets can be precisely partitioned. Its disadvantage is that partition pruning is difficult for range queries.
Applicable scenarios:
- Discrete fields (such as regions and channel types).
- Data must be pruned quickly by fixed categories (such as querying users in East China).
Design considerations:
Partition key selection:
- Discrete values with a limited number of values (for example, the
regionfield has only['east','west','south','north']). - Partition values must cover all possible values to avoid omissions.
- Discrete values with a limited number of values (for example, the
Number of partitions:
- Configure the number of partitions based on business logic.
Example scenario:
CREATE TABLE orders_by_region (
order_id BIGINT COMMENT 'Unique order identifier',
region_code INT NOT NULL PRIMARY KEY COMMENT 'Region code (1=north/china, 2=east/china, 3=south/china, 4=west/china)',
customer_id BIGINT COMMENT 'Customer ID',
order_time DATETIME COMMENT 'Order creation time',
product_category VARCHAR(50) COMMENT 'Product category',
order_amount DECIMAL(18,2) COMMENT 'Order amount',
payment_status VARCHAR(20) COMMENT 'Payment status (such as PAID and UNPAID)'
)
PARTITION BY LIST(region_code) -- The partition key is changed to an integer type.
(
PARTITION p_north VALUES IN (1), -- Region code 1 corresponds to north/china
PARTITION p_east VALUES IN (2),
PARTITION p_south VALUES IN (3),
PARTITION p_west VALUES IN (4),
PARTITION p_other VALUES IN (DEFAULT) -- The default partition handles unknown regions
);
Flexible partition management
OceanBase Database provides highly flexible partition management capabilities. From the perspective of data management, it supports both data maintenance and data distribution. From the perspective of usage, it supports both manual and automatic management. From the perspective of partition levels, it supports a combination of primary partitions and subpartitions. These combinations meet different user requirements for data management.
This section describes data maintenance and data distribution separately, and considers the combination of usage methods and partition levels from both perspectives.
Data maintenance
Businesses usually manage partitions by time to facilitate data archiving and cleanup. The following describes the manual partition management capabilities based on the complete data lifecycle of a business:
- Create the table: Create a table partitioned by time and pre-create the partitions required for an upcoming period.
- Import data: Import data.
- Run the business: As time goes on, the pre-created partitions may be insufficient. Continue to pre-create the partitions required for an upcoming period.
- Clean up data periodically: After data has accumulated for a period, the earlier data may no longer be needed. In this case, you can delete the partitions that are no longer needed.
Example:
-- 1. Create a partitioned table (partitioned by day, with the partitions of the next 7 days pre-created).
CREATE TABLE business_data (
id BIGINT NOT NULL AUTO_INCREMENT,
event_time DATETIME NOT NULL,
metric_value DECIMAL(10,2),
PRIMARY KEY (id, event_time)
) PARTITION BY RANGE COLUMNS(event_time) (
PARTITION p20231025 VALUES LESS THAN ('2023-10-26'),
PARTITION p20231026 VALUES LESS THAN ('2023-10-27'),
PARTITION p20231027 VALUES LESS THAN ('2023-10-28'),
PARTITION p20231028 VALUES LESS THAN ('2023-10-29'),
PARTITION p20231029 VALUES LESS THAN ('2023-10-30'),
PARTITION p20231030 VALUES LESS THAN ('2023-10-31'),
PARTITION p20231031 VALUES LESS THAN ('2023-11-01') -- Pre-create the partitions of the next 7 days.
);
-- 2. Import data. This step is omitted here.
-- 3. Pre-create the partitions of the next 7 days.
ALTER TABLE business_data ADD PARTITION (
PARTITION p20231101 VALUES LESS THAN ('2023-11-02'),
PARTITION p20231102 VALUES LESS THAN ('2023-11-03'),
PARTITION p20231103 VALUES LESS THAN ('2023-11-04'),
PARTITION p20231104 VALUES LESS THAN ('2023-11-05'),
PARTITION p20231105 VALUES LESS THAN ('2023-11-06'),
PARTITION p20231106 VALUES LESS THAN ('2023-11-07'),
PARTITION p20231107 VALUES LESS THAN ('2023-11-08')
);
-- 4. Clean up data periodically. For example, delete 7 days of data after it expires.
ALTER TABLE business_data DROP PARTITION p20231025, p20231026, p20231027, p20231028, p20231029, p20231030, p20231031;
Because data is continuously written, manually maintaining pre-created partitions and periodically cleaning up partitions is cumbersome. To simplify this process, OceanBase Database provides the dynamic partitioning feature, which supports partitioning by a fixed time interval, pre-creating partitions for a specified period, and retaining historical partitions for a specified period.
For the preceding example, if you want to retain data for 30 days and pre-create the partitions of 7 days each time, use the following syntax:
-- 1. Create a partitioned table and set the dynamic partitioning policy.
CREATE TABLE t1 (
id BIGINT NOT NULL AUTO_INCREMENT,
event_time DATETIME NOT NULL,
metric_value DECIMAL(10,2),
PRIMARY KEY (id, event_time))
DYNAMIC_PARTITION_POLICY
(
ENABLE = true,
TIME_UNIT = 'day',
PRECREATE_TIME = '7day',
EXPIRE_TIME = '30day'
)
PARTITION BY RANGE COLUMNS (event_time)(
PARTITION p20231025 VALUES LESS THAN ('2023-10-26'));
In addition to RANGE partitioning, businesses can choose other basic partitioning methods based on their requirements.
For more information about dynamic partitioning, see Dynamic partitioning, Create a dynamic partition table in MySQL mode, and Create a dynamic partition table in Oracle mode.
Data distribution
Partitions can also serve as units of data distribution management. To disperse data, HASH partitioning is generally used. It has the following advantages:
- It usually achieves even data distribution effectively and supports precise partition pruning based on the partition key.
- For multiple tables that need JOIN operations, if they are all HASH partitioned by the same join key and have the same number of partitions, together with the Table Group feature of OceanBase Database, partitions with the same hash value can be bound to the same group of nodes. This enables Partition-Wise Join during JOIN execution, avoids cross-node data shuffling, and significantly improves query performance.
HASH partitioning also has limitations:
- After the number of partitions of a HASH partitioned table is set, changing it is a heavy operation that involves rewriting the entire table. Therefore, once the number of partitions is set, it is rarely changed, which makes scaling difficult.
- For range queries on the partition key, partitions cannot be pruned, and all partitions must be accessed, which may cause read amplification.
To resolve the scalability and range query issues of HASH partitioning, OceanBase Database supports automatic partition splitting for rowstore tables.
Hybrid data maintenance and data distribution management
You can also use subpartitioning to support both data maintenance and data distribution requirements. A common scenario is that primary partitions are used for data maintenance and subpartitions are used for data distribution. Each requirement can be met by using the method supported for that requirement.
Typical manual partition management
- Primary partitions:
- Type selection: Use RANGE or LIST partitioning to match high-frequency query conditions (such as time ranges and regions).
- Recommended number of partitions: Set a proper range based on the time distribution of query conditions and data maintenance requirements (for example, partition by month and retain 12 months, or partition by region into 4 LIST partitions).
- Subpartitions:
- Type selection: Use HASH partitioning to ensure data dispersion.
- Recommended number of partitions:
- If only one primary partition is written to, the number of subpartitions in the primary partition must meet the resource requirements for write dispersion.
- If multiple primary partitions can be written to, the number of writable primary partitions multiplied by the number of subpartitions must meet the resource requirements for write dispersion.
The following are two example scenarios: RANGE + HASH and LIST + HASH:
RANGE + HASH
Choose RANGE partitioning for the primary partition. After you specify order_date, the partitions that do not need to be scanned can be filtered out quickly, and data maintenance can be performed quickly through partition management operations. Choose HASH partitioning for the subpartition to disperse the writes or reads of the current month across 8 partitions and avoid hotspots.
CREATE TABLE orders (
user_id BIGINT NOT NULL COMMENT 'User ID (subpartition key)',
order_date DATE NOT NULL COMMENT 'Order date (primary partition key)',
amount DECIMAL(10,2) NOT NULL COMMENT 'Order amount',
status TINYINT NOT NULL COMMENT 'Status: 0-canceled, 1-pending payment, 2-paid, 3-shipped, 4-completed',
region_code CHAR(6) NOT NULL COMMENT 'Region code (the first 2 digits are the province code)',
product_id INT NOT NULL COMMENT 'Product ID',
payment_method VARCHAR(20) COMMENT 'Payment method',
created_at TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) COMMENT 'Record creation time')
PARTITION BY RANGE COLUMNS(order_date)
SUBPARTITION BY HASH(user_id) SUBPARTITIONS 8
(
PARTITION p202501 VALUES LESS THAN ('2025-02-01'),
PARTITION p202502 VALUES LESS THAN ('2025-03-01'),
...
PARTITION p202601 VALUES LESS THAN ('2026-02-01')
);
LIST + HASH
Choose LIST partitioning for the primary partition, so that specifying a province prunes to the corresponding partition and data can be maintained by province. Choose HASH or KEY partitioning for the subpartition to disperse the read and write traffic of a province across multiple partitions for load balancing.
-- Primary partition: LIST partitioned by province (31 provincial-level administrative regions)
CREATE TABLE social_insurance_records (
record_id BIGINT,
province_code INT NOT NULL, -- Province code (for example, 11 for Beijing and 31 for Shanghai)
payment_date DATE NOT NULL,
user_id VARCHAR(32) NOT NULL,
amount DECIMAL(10,2)
) PARTITION BY LIST (province_code) -- Primary LIST partition
SUBPARTITION BY KEY(user_id) SUBPARTITIONS 16 -- Subpartitions are HASH partitions
(
PARTITION p_beijing VALUES IN (11),
PARTITION p_shanghai VALUES IN (31),
PARTITION p_tianjin VALUES IN (12),
...
PARTITION p_xizang VALUES IN (54)
);
Typical automatic partition management
- Primary partitions: Choose dynamic partitioning, and configure parameters such as the fixed time interval, how far ahead to pre-create partitions, and how long to retain historical partitions.
- Subpartitions: Choose automatic RANGE partition splitting, which splits partitions automatically without the need to configure the number of partitions or partitioning rules.