← Back to SQL, page 23

sql-0458 · Medium mid

A table holds ten years of orders, but almost all queries touch the last year. How would you handle the old data?

Separate hot and cold data: partition by date so recent partitions stay small and old ones can be moved, compressed or detached, or move old rows into an archive table or cheaper storage on a schedule. Keep the archive queryable when needed (a view over both, or a warehouse), and agree retention rules with the business and legal teams.

Full answer

Approaches:

  • Time partitioning: queries filtered by date prune old partitions; old partitions can sit on cheaper tablespaces or be detached and exported.
  • Archive tables: a monthly job moves rows older than N years into orders_archive in batches, inside transactions, with matching child rows (order lines, payments).
  • External storage: export old data to files in object storage or a warehouse, then delete it from the operational database.
  • Union view: CREATE VIEW all_orders AS SELECT ... FROM orders UNION ALL SELECT ... FROM orders_archive for occasional full-history reports.

Also consider:

  • Foreign keys: archiving parents requires archiving children together.
  • Indexes on the hot table shrink, which helps cache hit rates.
  • Retention law: tax records may need to be kept for a fixed number of years, while personal data may need to be removed sooner.

The goal is that daily operations only pay for the data they use.

Key points

  • Separate hot and cold data
  • Partition by time for pruning
  • Move old rows with their children
  • Keep archives queryable if needed
  • Follow retention rules

Common mistakes

  • Keeping everything in one ever-growing table without a plan
  • Archiving parents without children

Follow-ups

  • How would you restore an archived order on request?
  • How do partitions help with archiving?

Tips

  • Tie the approach to query patterns