✏️ Explanatory Question
Level: Expert — A powerful technique for managing and querying very large tables efficiently.
Partitioning is the process of dividing a single large table into smaller, more manageable pieces called partitions — while it still appears as one logical table to queries. Each partition is stored and can be managed separately.
| Type | Based On | Best For |
|---|---|---|
| RANGE | Value ranges | Time-series (by year/month) |
| LIST | Discrete value list | Categorical (region, status) |
| HASH | Hash of a column | Even data distribution |
| KEY | Internal hash function | Even distribution, any column type |
-- RANGE partitioning by year
CREATE TABLE sales (
id INT,
sale_date DATE,
amount DECIMAL(10,2)
)
PARTITION BY RANGE ( YEAR(sale_date) ) (
PARTITION p2023 VALUES LESS THAN (2024),
PARTITION p2024 VALUES LESS THAN (2025),
PARTITION p2025 VALUES LESS THAN (2026),
PARTITION pmax VALUES LESS THAN MAXVALUE
);
-- Query hits ONLY the p2025 partition (partition pruning)
SELECT * FROM sales
WHERE sale_date BETWEEN '2025-01-01' AND '2025-12-31';
-- LIST partitioning by region
CREATE TABLE customers (
id INT,
region VARCHAR(10)
)
PARTITION BY LIST COLUMNS(region) (
PARTITION p_east VALUES IN ('WB','BR','OD'),
PARTITION p_west VALUES IN ('MH','GJ','RJ')
);
-- HASH partitioning into 4 buckets
CREATE TABLE logs (
id INT,
msg TEXT
)
PARTITION BY HASH(id) PARTITIONS 4;
-- Fast maintenance: drop an entire old partition instantly
ALTER TABLE sales DROP PARTITION p2023;