MySQL Partition
How to use partitions in MySQL to improve performance. A few partitions, like India and Pakistan, were not essential, but partitioning an SQL table might be necessary based on the use cases. You have created the best schema for your table. All were going smoothly. Clients are happy, DevOps teams are so glad, less expense on Infra; Cloud is the best. MySQL (v5.7.41 onwards) snippet for partitioning your table by a DATETIME data type column. An event can be created per the above schema to delete the oldest partition before the new month’s data is ingested. With the above dynamic partition and event, let’s calculate the minimum days’ data will get stored in the table. In this post, we learned the following: Thank you. Why are Partitions Essential? 🤔
Dynamic partition creation ♻
/* Create command */
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`account_id` bigint(10) unsigned NOT NULL,
`product_id` bigint(10) unsigned NOT NULL,
`created_at` DATETIME(6) NOT NULL,
PRIMARY KEY (`id`, `created_at`),
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
PARTITION BY LIST(month(created_at)%3) (
PARTITION p0 VALUES IN (0),
PARTITION p1 VALUES IN (1),
PARTITION p2 VALUES IN (2)
);
/* Truncate command */
TRUNCATE PARTITION p0;
awesome_product
Event for auto truncation of partition ☠️
DROP EVENT IF EXISTS awesome_product_truncate_partition;
delimiter $$
CREATE EVENT awesome_product_truncate_partition
ON SCHEDULE
EVERY '1' DAY
DO
BEGIN
DECLARE day_of_month SMALLINT;
DECLARE month_of_year SMALLINT;
DECLARE NOW DATETIME;
SET NOW = NOW ;
SET day_of_month = dayofmonth(NOW);
SET month_of_year = MONTH(NOW);
IF day_of_month >= 22 AND day_of_month <=28 THEN
CASE month_of_year % 3
WHEN 0 THEN awesome_product TRUNCATE PARTITION p1;
WHEN 1 THEN awesome_product TRUNCATE PARTITION p2;
WHEN 2 THEN awesome_product TRUNCATE PARTITION p0;
END CASE;
END IF;
END
$$
Data retention period ⏳
Summary 📝