[TiDB Usage Environment] Production Environment
[TiDB Version] 6.5.0
I want to partition the data table by month. Is there a way to automatically partition by month? I see that the current tutorials generally require separate configuration for each month, such as:
ADD PARTITION (
PARTITION p202001 VALUES LESS THAN (UNIX_TIMESTAMP(‘2020-02-01 00:00:00’)),
PARTITION p202002 VALUES LESS THAN (UNIX_TIMESTAMP(‘2020-03-01 00:00:00’)),
…
PARTITION p202006 VALUES LESS THAN (UNIX_TIMESTAMP(‘2020-07-01 00:00:00’)),
If configured as above, when it comes to August, I need to manually add partitions again.
In Range partitioning, you can partition based on the value of the timestamp column and use the unix_timestamp() function, for example:
CREATE TABLE quarterly_report_status (
report_id INT NOT NULL,
report_status VARCHAR(20) NOT NULL,
report_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
PARTITION BY RANGE ( UNIX_TIMESTAMP(report_updated) ) (
PARTITION p0 VALUES LESS THAN ( UNIX_TIMESTAMP('2008-01-01 00:00:00') ),
PARTITION p1 VALUES LESS THAN ( UNIX_TIMESTAMP('2008-04-01 00:00:00') ),
PARTITION p2 VALUES LESS THAN ( UNIX_TIMESTAMP('2008-07-01 00:00:00') ),
PARTITION p3 VALUES LESS THAN ( UNIX_TIMESTAMP('2008-10-01 00:00:00') ),
PARTITION p4 VALUES LESS THAN ( UNIX_TIMESTAMP('2009-01-01 00:00:00') ),
PARTITION p5 VALUES LESS THAN ( UNIX_TIMESTAMP('2009-04-01 00:00:00') ),
PARTITION p6 VALUES LESS THAN ( UNIX_TIMESTAMP('2009-07-01 00:00:00') ),
PARTITION p7 VALUES LESS THAN ( UNIX_TIMESTAMP('2009-10-01 00:00:00') ),
PARTITION p8 VALUES LESS THAN ( UNIX_TIMESTAMP('2010-01-01 00:00:00') ),
PARTITION p9 VALUES LESS THAN (MAXVALUE)
);
For the timestamp column, using other partition expressions is not allowed.
It’s better to create it in advance. Even if there is an automatic partitioning feature, I don’t think it’s reliable. TiDB’s DDL cannot be executed concurrently, and executing it multiple times will always encounter issues with execution getting stuck. Partition table operations, in particular, are prone to problems.
Creating the database in advance also has its benefits. Sometimes the DDL for TiDB partitions can get stuck, so it’s better to choose an appropriate time to do it.