← Back to SQL, page 17

sql-0326 · Hard senior

A table of sensor readings grows by 100 million rows a month. How would you keep queries and maintenance manageable?

Partition the table by time, for example one partition per month, so queries for recent data touch only recent partitions and old data can be dropped by detaching a partition instead of running huge DELETEs. Index within partitions on (sensor_id, ts), roll up old raw data into hourly or daily aggregates, and consider a time-series extension or columnar store for analytics.

Full answer

PostgreSQL declarative partitioning:

text
CREATE TABLE readings (sensor_id int, ts timestamptz, value double precision)
  PARTITION BY RANGE (ts);
CREATE TABLE readings_2026_03 PARTITION OF readings
  FOR VALUES FROM ('2026-03-01') TO ('2026-04-01');

Benefits:

  • Partition pruning: WHERE ts >= now() - interval '1 day' scans only the newest partition.
  • Retention: DROP TABLE readings_2025_01 is instant, unlike deleting 100 million rows.
  • Smaller indexes per partition, and maintenance (VACUUM, reindex) per partition.

Also plan:

  • Rollups (hourly averages, min, max) for dashboards, so raw data can expire sooner.
  • Batched inserts or COPY instead of row-by-row inserts.
  • Queries that always include the partition key, or pruning cannot help.

SQLite has no partitioning; at this volume it is usually the wrong engine, though per-period database files are a workable pattern for embedded use. The PostgreSQL DDL above is shown for illustration and was not run here.

Key points

  • Partition by time for pruning and cheap retention
  • Drop old partitions instead of mass DELETE
  • Roll up raw data into aggregates
  • Queries must filter on the partition key
  • Batch inserts at high volume

Common mistakes

  • Deleting old rows in one huge DELETE
  • Partitioning by a column that queries do not filter on

Follow-ups

  • How many partitions are too many?
  • When would a columnar store be better?

Tips

  • Name pruning and retention as the two wins