Difficulty: Intermediate
How do you handle very large tables containing years of old, rarely accessed data?
Separate hot data from cold data. Keep recent rows in the main table, move older rows to an archive table, cheaper storage or object storage like S3 in a columnar format such as Parquet, and delete what you are no longer required to keep. The cleanest way to do this in PostgreSQL or MySQL is time-based partitioning, where archiving becomes detaching or dropping a whole partition instead of deleting millions of rows.
Most applications only query recent data. An order history page shows the last few months; older data is needed for audits, tax or analytics.
Partition the table by month or quarter (for example PARTITION BY RANGE (created_at) in PostgreSQL). Then:
created_at only touch relevant partitions (partition pruning).ALTER TABLE ... DETACH PARTITION (with CONCURRENTLY since PostgreSQL 14), followed by export and DROP TABLE.DELETE.pg_partman create future partitions and retire old ones automatically.If partitioning is not an option, move old rows with a background job:
orders_archive or export it.Large deletes leave dead tuples in PostgreSQL, so autovacuum must keep up; partitioning avoids that problem entirely.
| Destination | Good for | Access |
|---|---|---|
| Archive table in the same database | Occasional lookups by support teams | Plain SQL, slower is fine |
| Separate archive database | Keeps primary small, still SQL | Cross-database queries |
| S3 or GCS as Parquet | Cheap long-term retention and analytics | Athena, BigQuery, Spark, DuckDB |
| Glacier-class storage | Compliance copies rarely read | Hours to restore |
TTL features are an alternative for data that can simply expire: DynamoDB TTL and MongoDB TTL indexes delete items automatically after a timestamp.
CREATE TABLE payments (
id BIGINT GENERATED ALWAYS AS IDENTITY,
merchant_id BIGINT NOT NULL,
amount_paise BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (id, created_at) -- partition key must be in the PK
) PARTITION BY RANGE (created_at);
CREATE TABLE payments_2026_10 PARTITION OF payments
FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
-- Archive an old month: detach without blocking queries (PG 14+)
ALTER TABLE payments DETACH PARTITION payments_2023_10 CONCURRENTLY;
-- export payments_2023_10 to Parquet/S3, verify, then:
DROP TABLE payments_2023_10;
Detaching and dropping a partition replaces a slow, bloating DELETE of millions of rows with a near-instant metadata operation.
-- Run in a loop from a job until 0 rows are moved
WITH moved AS (
DELETE FROM orders
WHERE id IN (
SELECT id FROM orders
WHERE created_at < now() - interval '2 years'
LIMIT 5000
)
RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;
The writable CTE deletes and archives the same batch atomically, keeping each transaction short.
Data Archiving, Table Partitioning, Cold Storage, Data Retention, Batch Deletes