Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A 4 TB orders table has queries filtered by customer_id and by created_at, and old data must be deleted after 7 years. Would you partition it, and by what key? How would you migrate the live table?

Yes, I would partition it by range on created_at, usually monthly, because that turns the 7-year retention into detaching and dropping a partition instead of deleting billions of rows, and keeps vacuum and index maintenance per partition. Queries by customer_id alone will then check every partition, so I would measure that cost before deciding. To migrate the live table, I would attach the existing table as one large partition after proving its range with a CHECK constraint, or copy it in batches with logical replication and switch over.

Why this question is asked

Very large tables are where partitioning decisions get real: a wrong key makes every query slower, and a careless migration can lock a 4 TB table for hours. Interviewers ask this because a good answer weighs the access paths against the retention rule, notices how the primary key and foreign keys change, and plans a migration that never stops the business. In this answer, we will look at what each candidate key gives us, check the cost for customer_id queries, see what happens to keys and Hibernate entities, and then walk through two ways to migrate the live table.

1A Quick Recap: What We Want From Partitioning Here

Partitioning splits one logical table into child tables, each owning a range or set of key values. It does not make a well-indexed single-row lookup faster by itself. What it gives us is smaller units of maintenance, and the ability to remove a whole slice of data as a metadata operation.

Our table has two query patterns, by customer_id and by created_at, and one hard rule: data older than 7 years must go. The retention rule is about time, and that is the strongest hint about the key.

2Choosing the Partition Key

Without partitioning, retention means a nightly DELETE of perhaps 50 million rows. That writes WAL for every row, leaves dead tuples that vacuum must clean, bloats indexes, and competes with live traffic. With monthly range partitions on created_at, retention becomes two quick statements: detach the oldest month and drop it. The space comes back immediately and no vacuum is needed.

Range partitioning by created_at also helps the time-filtered queries, because pruning skips every month outside the filter. And autovacuum works per partition, so the current month is vacuumed often while seven-year-old partitions sit untouched.

SQL
ALTER TABLE orders DETACH PARTITION orders_2018_11 CONCURRENTLY; -- PostgreSQL 14+, no long lock on the parent
DROP TABLE orders_2018_11; -- about 50 GB freed at once
Candidate keys for a 4 TB orders table
KeyRetentionQuery by customer_idQuery by created_at
range on created_at (monthly)detach and drop, instantchecks all ~84 partitionsprunes to the months asked for
hash on customer_id (32)large DELETEs in every partitionprunes to one partitionchecks all 32 partitions
no partitioninglarge DELETEs, vacuum, bloatone index lookupone index range scan
Retention is about time, so range on created_at usually wins.

The other candidate is hash partitioning on customer_id, which spreads customers evenly over, say, 32 partitions and lets customer queries prune to one. But it does nothing for retention: every hash partition contains orders of every age, so we are back to large DELETEs. We would only choose it if customer_id were by far the main access path and retention were rare.

3The Cost for Queries by customer_id

With monthly partitions over 7 years we have about 84 partitions. A query WHERE customer_id = 42 cannot be pruned, so PostgreSQL runs 84 small index scans, one per partition's local index on customer_id. Each probe costs a few page reads, so a query that took 1 ms before might take 5 to 10 ms. For a customer's order history page that is usually acceptable, and if the query also says created_at > now() - interval '1 year', it prunes down to 12 or 13 partitions.

So the decision rests on measurement. We take the real customer queries, run them against a test copy partitioned monthly, and compare latency and planning time. If they are too slow, yearly partitions (7 instead of 84) or asking the API to always send a date range are cheaper fixes than giving up the retention benefit.

4What Happens to Keys and Hibernate Entities

A unique constraint on a partitioned table must include the partition key, so the primary key becomes (id, created_at). Every foreign key that references orders, from order_items or payments, must then reference both columns, which means adding order_created_at to those tables. PostgreSQL 12 and later allow foreign keys that reference a partitioned table.

In Hibernate we have two choices. We can map the full key with @IdClass or @EmbeddedId so that every update and delete says WHERE id = ? AND created_at = ?, which prunes to one partition. Or we can keep @Id on id alone, which works because ids from a sequence stay unique in practice, but then every update by id has to probe all partitions, and the database no longer guarantees id is unique on its own.

Java
@Entity @Table(name = "orders") @IdClass(OrderKey.class)
class Order {
@Id Long id;
@Id @Column(name = "created_at") OffsetDateTime createdAt;
Long customerId;
}
record OrderKey(Long id, OffsetDateTime createdAt) implements Serializable {}
// update orders set ... where id=? and created_at=? -> one partition

The composite key is more typing but it is honest about the table, and the pruned updates matter on a busy table.

5Migrating the Live Table

The fastest path reuses the existing table. We create the new partitioned table, then attach the old 4 TB table as one partition covering everything up to the cutover date, and new months go into fresh partitions. Attaching normally scans the whole table to prove every row fits the bounds, which would take hours. To avoid that, we first add a CHECK constraint with the same range as NOT VALID, validate it (which scans but only takes a lock that allows reads and writes), and then ATTACH sees the proven constraint and skips its own scan. We also build the (id, created_at) unique index on the old table CONCURRENTLY beforehand, so ATTACH does not build it under a lock.

SQL
ALTER TABLE orders RENAME TO orders_legacy;
CREATE TABLE orders (LIKE orders_legacy INCLUDING DEFAULTS) PARTITION BY RANGE (created_at);
CREATE TABLE orders_2026_12 PARTITION OF orders FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
ALTER TABLE orders_legacy ADD CONSTRAINT legacy_range
CHECK (created_at < '2026-12-01') NOT VALID;
ALTER TABLE orders_legacy VALIDATE CONSTRAINT legacy_range; -- scans, but reads and writes continue
ALTER TABLE orders ATTACH PARTITION orders_legacy
FOR VALUES FROM (MINVALUE) TO ('2026-12-01'); -- no scan: the CHECK proves it
Step throughMigration by attaching the old table
  1. Build (id, created_at) unique index CONCURRENTLYno blocking
  2. Add CHECK ... NOT VALID, then VALIDATEfull scan, reads and writes allowed
  3. Rename and create the partitioned parentshort transaction
  4. ATTACH old table as one big partitionno scan because of the CHECK
  5. Create future months ahead of timepg_partman or a scheduled job
  6. Split the legacy partition over timeso retention can drop it

6 steps in order. Play them, or step through them one at a time.

The renaming and creation run in one short transaction during a quiet moment. The catch is that the legacy partition still holds 7 years, so retention for that slice stays a DELETE until we split it, for example by copying a year at a time into proper partitions in the background. The alternative migration avoids that: build a fully partitioned copy, fill it by copying in batches while triggers or logical replication carry new changes, compare counts, and switch the application during a short write pause. It takes longer and needs twice the disk, but ends with a clean layout.

6Keeping It Healthy Afterwards

Partitions must exist before data arrives, so we automate creation with pg_partman or a scheduled job that creates the next three months, and alert if the next month's partition is missing. A default partition is useful as a safety net but should stay empty, and an alert on any rows in it tells us the automation failed. Retention is a scheduled job too, detaching and dropping partitions older than 84 months, ideally after an archive copy if the business needs one.

7Follow-up questions

What happens to Hibernate entities when the primary key becomes composite?

The entity needs @IdClass or @EmbeddedId with both id and created_at, and every repository method that loads by id now needs the created_at too, so APIs and caches that pass only the id must change. The benefit is that updates and deletes include the partition key and touch one partition. Keeping @Id on id alone also works but makes updates probe every partition and loses the database's guarantee that id alone is unique.

Would you partition by customer_id at all?

Only if customer queries dominated and retention were not time based. An option for both needs is range on created_at with a local index on customer_id, then measure; sub-partitioning by hash inside each month is possible but multiplies the partition count and is rarely worth it.

8Conclusion

In this answer, we chose monthly range partitioning on created_at because the retention rule becomes DETACH and DROP instead of huge DELETEs, and vacuum works per partition. We checked that customer_id queries would probe every partition and decided to measure that rather than guess. We saw that the primary key and foreign keys must include created_at, which changes Hibernate mappings, and we planned the migration either by attaching the old table after a validated CHECK constraint or by copying in batches and switching, with automated partition creation and alerts afterwards.

What to say in the interviewAbout 90 seconds aloud

Open with

I would partition by range on created_at, monthly, because the hard requirement is deleting data after 7 years. With partitions, retention is detach and drop, which frees the space instantly instead of a huge DELETE that writes WAL, bloats indexes and needs vacuum.

Then, if they want more

Autovacuum also works per partition. The cost is that a query on customer_id alone checks all 84 partitions' local indexes, so I would measure real customer queries on a test copy; often it is a few milliseconds more, and adding a date range to the query prunes most partitions.

If customer lookups were the dominant path and retention did not matter, hash on customer_id would be the alternative. Unique constraints must include the partition key, so the primary key becomes id plus created_at, foreign keys from order_items need created_at, and Hibernate entities move to @IdClass or @EmbeddedId.

For the migration, I would build the matching unique index concurrently, add a CHECK constraint as NOT VALID and validate it, then attach the old table as one legacy partition, which skips the long scan, and send new months to new partitions. Later I would split the legacy partition.

If we can afford the disk, copying in batches with logical replication and a short switchover gives a cleaner result. Finally, pg_partman or a scheduled job creates future partitions, with an alert when one is missing.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12, PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
PostgreSQL documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A 4 TB orders table has queries filtered by customer_id and by created_at, and old data...": https://scrivio-interview-library.netlify.app/databases/postgresql/5119048e6b/