dataiotech Labs
Back to Performance Guide
[Engine-Agnostic]BLUEPRINTPostgreSQL 16 / 17, MySQL 8.4 LTS, SQL Server 202226 minSenior DBA / SRE + Backend Developer + Mimar

[Universal] BLUEPRINT: Partitioning — When to Split, When Not to Split

Partitioning is the most misunderstood medicine in the database world. Not every large table should be partitioned. Wrong partitioning slows the table instead of speeding it up, complicates queries, and makes maintenance harder. Correct partitioning makes even a billion-row table manageable. In this guide you will learn what partitioning is, the decision tree for when to split and when not to split, the 3 main partitioning types, the live migration plan, and the 7 most common mistakes. This article completes the Universal leg of the Performance Pillar.

Production Incident Scenario

There is a table. `logs` table, 800 million rows. Every day 5 million new rows are added. Queries are getting slower. Vacuum cannot keep up. Creating an index takes 6 hours. Deleting old data with `DELETE` takes hours and creates locks. The team says we must partition the table. The DBA says partitioning does not solve everything. Both are right. Because the table should be partitioned, but with the right key, the right type, and the right migration plan. If partitioned wrong, an 800-million-row problem becomes a 24-partition 800-million-row problem. This guide shows how to partition that table correctly.

Summary

Partitioning is the most misunderstood medicine in the database world. Not every large table should be partitioned. Wrong partitioning slows the table instead of speeding it up, complicates queries, and makes maintenance harder. Correct partitioning makes even a billion-row table manageable. In this guide you will learn what partitioning is, the decision tree for when to split and when not to split, the 3 main partitioning types, the live migration plan, and the 7 most common mistakes. This article completes the Universal leg of the Performance Pillar.

Scenario

There is a table. logs table, 800 million rows. Every day 5 million new rows are added. Queries are getting slower. Vacuum cannot keep up. Creating an index takes 6 hours. Deleting old data with DELETE takes hours and creates locks. The team says we must partition the table. The DBA says partitioning does not solve everything. Both are right. Because the table should be partitioned, but with the right key, the right type, and the right migration plan. If partitioned wrong, an 800-million-row problem becomes a 24-partition 800-million-row problem. This guide shows how to partition that table correctly.

Concept: What Is Partitioning?

Partitioning splits a large table physically into smaller pieces. But logically the table is still one table. The application queries one table. The database decides which piece is needed and reads only that piece.

Analogy: Think of a 1000-page encyclopedia. Carrying it as one volume is hard. If you split it into 10 volumes, you take only the volume you need. But if you split the encyclopedia wrong, for example putting random pages in each volume, you must check all 10 volumes to find a topic. Partitioning is the same. Split correctly, you get faster. Split wrong, you get slower.

▸What Partitioning Is Not

Partitioning is not sharding. Sharding splits data across different servers. Partitioning splits data into different physical pieces on the same server.

Partitioning is not an index. An index helps you find the row quickly. Partitioning reduces the amount of data to read. They complement each other but do not replace each other.

Partitioning is not a magic wand. It does not fix a bad query. It does not fix a bad index. It does not fix N+1. Fix those first, then think about partitioning.

Decision Tree: Should You Split?

This is the most important section of this guide. Do not partition without answering this question.

▸Split If — At Least 3 of These 5 Conditions Exist

1. The table is really large.

Do not partition a 100-thousand-row table. Over 10 million rows is the lower limit for partitioning. Over 100 million rows is a strong reason. Partitioning a small table increases management cost without benefit.

2. Queries filter by the partition key.

For example, if 90% of queries run with WHERE created_at BETWEEN ... and you partition the table by created_at, the query reads only the relevant piece. This is the biggest win of partitioning. It is called partition pruning.

3. Old data is regularly deleted or archived.

If you delete data older than 6 months every month, with partitioning the delete becomes DROP PARTITION instead of DELETE. DELETE takes hours, creates locks, requires vacuum. DROP PARTITION takes seconds, creates no locks, needs no vacuum. This alone is enough reason to partition.

4. Vacuum and index maintenance cannot keep up on a single table.

On an 800-million-row table, vacuum must scan the whole table. With partitioning, vacuum works only on the active partition. Old partitions do not change, so they do not need vacuum. Maintenance load drops dramatically.

5. Data lifecycle is different.

If last 30 days data is read frequently, old data is read rarely, with partitioning you can keep hot data on fast disk and cold data on slow disk. This is called tiered storage.

▸Do Not Split If — Even One of These Exists, Stop

1. Queries do not use the partition key.

You partitioned by created_at but most queries run with WHERE customer_id = 123. Then every query must scan all partitions. This is slower than an unpartitioned table. Because planning and merging 24 partitions adds extra cost.

2. Joins are made outside the partition key.

You partitioned orders by created_at, but most joins are on customer_id. Then the join must be done separately with every partition. The plan gets complex, performance drops.

3. The table is still small.

Do not partition a 1-million-row table. First fix indexes, queries, vacuum. Partitioning is the last resort, not the first.

4. The partition key changes constantly.

The partition key determines which piece a row belongs to. If that key is updated frequently, the row constantly moves between pieces. This increases write cost and creates locks. The partition key should be a column that almost never changes. Like created_at, tenant_id, country_code.

5. The team is not ready to manage partitioning.

Partitioning requires maintenance. Every month a new partition must be created, old partitions must be archived or deleted. If this is not automated, one day a new partition will not be created and writes will fail. If the team cannot build this automation, do not partition.

3 Main Partitioning Types

▸1. Range Partitioning — Most Common, Safest

You split data by a range. The most common use is splitting by date.

PostgreSQL example:

sql
CREATE TABLE orders ( id bigint, created_at timestamptz NOT NULL, customer_id bigint, total numeric ) PARTITION BY RANGE (created_at); CREATE TABLE orders_2026_11 PARTITION OF orders FOR VALUES FROM ('2026-11-01') TO ('2026-12-01'); CREATE TABLE orders_2026_12 PARTITION OF orders FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');

MySQL example:

sql
CREATE TABLE orders ( id BIGINT, created_at DATETIME NOT NULL, customer_id BIGINT, total DECIMAL(12,2) ) PARTITION BY RANGE (TO_DAYS(created_at)) ( PARTITION p202611 VALUES LESS THAN (TO_DAYS('2026-12-01')), PARTITION p202612 VALUES LESS THAN (TO_DAYS('2027-01-01')), PARTITION pmax VALUES LESS THAN MAXVALUE );

When to use: Data filtered by date, ID range, numeric range.

Advantage: Deleting old data with DROP PARTITION takes seconds. Partition pruning is very effective.

Warning: Do not forget to add MAXVALUE or a default partition for the last partition. Otherwise out-of-range data cannot be written and the application gets an error.

▸2. List Partitioning — For Categorical Data

You split data by a list. The most common use is splitting by country, region, tenant.

PostgreSQL example:

sql
CREATE TABLE customers ( id bigint, country_code text NOT NULL, name text ) PARTITION BY LIST (country_code); CREATE TABLE customers_tr PARTITION OF customers FOR VALUES IN ('TR'); CREATE TABLE customers_de PARTITION OF customers FOR VALUES IN ('DE', 'AT', 'CH');

When to use: Columns with a small number of distinct values like country, tenant, region, category.

Advantage: Each tenant's data is physically separate. Deleting, archiving, or moving one tenant is very easy.

Warning: When a new country or tenant is added, do not forget to create a new partition. Otherwise that country's data cannot be written.

▸3. Hash Partitioning — For Even Distribution

You split data with a hash function. The database decides which row goes to which piece.

PostgreSQL example:

sql
CREATE TABLE events ( id bigint, user_id bigint, event_type text, created_at timestamptz ) PARTITION BY HASH (user_id); CREATE TABLE events_0 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 0); CREATE TABLE events_1 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 1); CREATE TABLE events_2 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 2); CREATE TABLE events_3 PARTITION OF events FOR VALUES WITH (MODULUS 4, REMAINDER 3);

When to use: When you want even distribution but will not query a single partition alone.

Advantage: Data is evenly distributed. No single partition gets bloated.

Disadvantage: If you query by date range, all partitions are scanned. Partition pruning does not work. So do not use Hash for date queries.

▸Which Type Should You Choose? Decision Table

SituationType
Filter by date, delete old dataRange
Filter by country / tenant / regionList
Even distribution, no single-partition queryHash
Date + tenant togetherRange + List (Subpartition)

Subpartition combines two types. For example, first split by date, then split each date partition by tenant. It is powerful but management is complex. Start with single-layer partitioning, move to subpartition only if needed.

Partitioning + Index Relationship

Partitioning does not remove indexes. On the contrary, index strategy changes.

▸Rule 1: Partition Key Must Be in the Index

If the partition key is created_at, most queries must include WHERE created_at BETWEEN .... But partition key alone is not enough for the index. The other filters of the query also need an index.

Example:

sql
-- Partition: RANGE (created_at) -- Query: SELECT * FROM orders WHERE created_at BETWEEN '2026-11-01' AND '2026-11-30' AND customer_id = 123; -- Correct index: CREATE INDEX idx_orders_customer ON orders (customer_id, created_at);

Partition pruning finds which piece to read with created_at. The index finds which row to read inside that piece. They work together.

▸Rule 2: Global Index vs Local Index Difference

In PostgreSQL, each partition has its own index. This is called a local index. A global index is a single index covering all partitions. In PostgreSQL 16 and 17, global index support is limited. So you must create a separate index for each partition. When you create a new partition, do not forget to create its indexes.

▸Rule 3: Primary Key Must Include the Partition Key

In a partitioned table in PostgreSQL, the Primary Key must include the partition key. For example, if the table is partitioned by created_at, the Primary Key must be (id, created_at). It cannot be just (id). This makes a difference on the application side. Because even when searching a single row by id, created_at information may be needed.

Live Migration Plan — 5 Steps

If partitioning is applied to an existing table, the migration plan is critical. Unplanned migration is a production incident.

▸Step 1: Create the New Partitioned Table

Do not change the existing table. Create a new table.

sql
CREATE TABLE orders_new ( LIKE orders INCLUDING ALL ) PARTITION BY RANGE (created_at);

▸Step 2: Create Partitions and Indexes

sql
CREATE TABLE orders_new_2026_11 PARTITION OF orders_new FOR VALUES FROM ('2026-11-01') TO ('2026-12-01'); CREATE INDEX idx_orders_new_customer ON orders_new (customer_id, created_at);

▸Step 3: Move Data in Pieces

Do not move all data at once. Move in pieces.

sql
-- First move one month, test it INSERT INTO orders_new SELECT * FROM orders WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01';

After each piece, verify row counts:

sql
SELECT count(*) FROM orders WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01'; SELECT count(*) FROM orders_new WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01';

If numbers are not equal, stop. Do not continue.

▸Step 4: Swap Table Names — Short Maintenance Window

sql
-- In the maintenance window, stop write traffic ALTER TABLE orders RENAME TO orders_old; ALTER TABLE orders_new RENAME TO orders;

This step takes seconds but locks the table. Do it in a maintenance window. Do not do it during daytime.

▸Step 5: Verify and Keep the Old Table

Run with the new table for 24 hours. Check queries, vacuum, indexes. If there is no problem, do not delete the old table immediately. Keep it for 7 days. If a problem occurs, you need it for rollback.

sql
-- After 7 days, if there is no problem DROP TABLE orders_old;

Partition Automation — If You Forget, the System Stops

The most dangerous part of partitioning is that if automation is forgotten, the system stops. Every month a new partition must be created. Doing it manually is doomed to be forgotten one day.

▸3 Options for Automation

Option 1: pg_partman (Recommended for PostgreSQL)

sql
CREATE EXTENSION pg_partman; SELECT partman.create_parent( p_parent_table => 'public.orders', p_control => 'created_at', p_type => 'range', p_interval => 'monthly', p_premake => 2 );

pg_partman creates next 2 months partitions in advance. It automatically archives or deletes old partitions.

Option 2: Scheduled Job (Cron + SQL)

A job running on the 1st of every month creates next month's partition.

sql
-- Example: Create next month's partition CREATE TABLE orders_2027_01 PARTITION OF orders FOR VALUES FROM ('2027-01-01') TO ('2027-02-01');

Option 3: Application-Side Control

The application checks before writing if a partition exists. If not, it creates it. But this mixes application and database responsibilities. Not recommended.

Practical advice: Use pg_partman. Manual partition management is not sustainable in production.

Verification: Did Partitioning Work?

After migration, answer 3 questions:

▸1. Does Partition Pruning Work?

sql
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE created_at BETWEEN '2026-11-01' AND '2026-11-30' AND customer_id = 123;

Only 1 partition should appear in the output. If 24 partitions appear, pruning does not work. The query does not use the partition key.

▸2. Did Old Data Deletion Get Faster?

Old delete with DELETE took hours, now DROP PARTITION should take seconds.

sql
-- Before: DELETE FROM orders WHERE created_at < '2026-01-01'; -- Takes hours -- Now: DROP TABLE orders_2025_12; -- Takes seconds

▸3. Did Vacuum and Maintenance Get Lighter?

sql
SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables WHERE relname LIKE 'orders_%' ORDER BY n_dead_tup DESC;

Except the active partition, n_dead_tup should be close to zero. Old partitions do not change, so they do not need vacuum.

7 Common Mistakes

First mistake: Partitioning a small table. Partitioning a 1-million-row table brings management load, not benefit.

Second mistake: Partitioning by a key queries do not use. Partitioning by created_at and querying by customer_id scans all partitions.

Third mistake: Forgetting to add MAXVALUE to the last partition. Out-of-range data cannot be written, the application gets an error.

Fourth mistake: Forgetting the new partition's index. If the new partition stays without an index, that month's queries do Seq Scan.

Fifth mistake: Not building automation. Manual partition management will be forgotten one day and the system will stop.

Sixth mistake: Constantly updating the partition key. The row constantly moves between pieces, write cost increases.

Seventh mistake: Trying to fix a bad query with partitioning. First fix the query, index, vacuum. Partitioning is the last resort.

Checklist

  • Table is over 10 million rows checked
  • 80% of queries use the partition key checked
  • Need for old data deletion / archiving verified
  • Partition type chosen with decision table (Range / List / Hash)
  • Partition key almost never changes checked
  • Primary Key includes partition key checked
  • New partitioned table created
  • Partitions and indexes created
  • Data moved in pieces, row counts verified
  • Table name swap done in maintenance window
  • Old table kept for 7 days
  • Partition pruning verified with EXPLAIN
  • Deletion with DROP PARTITION tested
  • Partition automation (pg_partman / cron) set up
  • Next month's partition is created in advance checked

Conclusion

Partitioning is a powerful tool that makes a large table manageable. But it does not apply to every large table. First look at the decision tree, then choose the type, then migrate in pieces, then set up automation. If you break this order, partitioning becomes the problem itself, not the solution.

This article completes the Universal leg of the Performance Pillar. Next is the MySQL leg.

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [Universal] N+1 Query Problem and Connection Pool Relationship
  • •Cluster: [Universal] EXPLAIN ANALYZE Reading Guide
  • •Cluster: [Universal] Connection Pool Sizing
  • •Cluster: [PostgreSQL] Vacuum / Analyze — Autovacuum Tuning
  • •Cluster: [PostgreSQL] Index Selection — B-Tree, Hash, GiST, GIN, BRIN When?
  • •Next: [MySQL] Finding the 20 Most Expensive Queries with Performance Schema
Operational Checklist

Verify each operational safety check before completing the task: