Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Using a data-modifying CTE in PostgreSQL, move all orders older than two years from orders to orders_archive in one statement, and explain the consistency guarantees and limits.

We write WITH moved AS (DELETE FROM orders WHERE created_at < now() - interval '2 years' RETURNING *) INSERT INTO orders_archive SELECT * FROM moved. Both parts run in one statement, one transaction and one snapshot, so every row is either still in orders or already in orders_archive, never in neither. The limits are that sub-statements see each other only through RETURNING, that a huge single statement holds locks and generates a lot of WAL, so we batch it, and that we should list columns explicitly.

Why this question is asked

Archiving old rows is a job almost every system needs, and it is easy to get wrong. The usual two-step version, copy then delete, has a gap between the steps, and a careless retry can copy rows twice or delete rows that were never copied. Interviewers ask for the data-modifying CTE because it shows we know PostgreSQL can do both in one atomic statement, and because the follow-up questions about locks, WAL and schema drift show whether we have run such jobs in production. In this answer, we will recap data-modifying CTEs, write the statement, explain its consistency guarantees and their limits, turn it into a safe batched job, and make it robust against schema changes.

1A Quick Recap of Data-Modifying CTEs

In PostgreSQL, a CTE does not have to be a SELECT. It can be an INSERT, UPDATE or DELETE with a RETURNING clause. RETURNING makes the statement hand back the rows it affected, as if it were a query, and the rest of the statement can read those rows by the CTE's name.

So a DELETE ... RETURNING * inside a CTE removes rows and, at the same moment, produces exactly those rows for the main query to use. That is the whole trick: the rows we insert into the archive are, by construction, the rows we deleted.

2The One-Statement Move

Here is the statement in its simplest form, followed by a check of the result.

SQL
WITH moved AS (
DELETE FROM orders
WHERE created_at < now() - interval '2 years'
RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;
-- INSERT 0 48210
SELECT count(*) FROM orders WHERE created_at < now() - interval '2 years'; -- 0
SELECT count(*) FROM orders_archive; -- 48210
Step throughOne statement, one snapshot
ApplicationPostgreSQLordersorders_archive
WITH moved AS (DELETE ... RETURNING *) INSERT ...
delete rows older than two years
deleted rows via RETURNING
insert exactly those rows
commit both changes together
INSERT 0 48210

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

The archive receives exactly the rows the DELETE removed, and both changes commit or roll back as one.

The command tag INSERT 0 48210 reports the rows inserted into the archive, which equals the rows deleted from orders, because the INSERT reads nothing except the RETURNING output. There is no second query that could pick a different set of rows.

3What Consistency It Guarantees

A single SQL statement is atomic: in PostgreSQL it runs inside a transaction, either an explicit one or an implicit one wrapped around the statement. If the INSERT fails, for example because of a duplicate key in orders_archive or a full disk, the DELETE is rolled back too. So there is no state, at any moment, in which a row has left orders but not arrived in orders_archive.

Other sessions never see the halfway point either. Until we commit, they see the rows in orders; after the commit, they see them in orders_archive. A report that counts both tables in one query, with its own snapshot, always gets the same total.

Compare that with the two-statement version, INSERT INTO orders_archive SELECT ... followed by DELETE FROM orders WHERE .... Even in one transaction, the two statements evaluate now() and the WHERE clause separately (now() is fixed per transaction, but a row inserted or updated between them in READ COMMITTED can match one statement and not the other). The CTE removes that whole class of problem.

4The Limits: Sub-Statements Cannot See Each Other

All sub-statements of a WITH query run with the same snapshot. That means they cannot see each other's changes to the tables. The only channel between them is RETURNING.

Notice what this means in practice. If the main query ran SELECT count(*) FROM orders WHERE created_at < now() - interval '2 years', it would still see the rows that the CTE is deleting, because it reads the snapshot from before the statement. And if two sub-statements modified the same row, the result would be unpredictable, which PostgreSQL's documentation warns against. So we keep the pattern simple: one DELETE that produces rows, one INSERT that consumes them through RETURNING.

SQL
WITH moved AS (
DELETE FROM orders WHERE created_at < now() - interval '2 years' RETURNING id
)
SELECT (SELECT count(*) FROM moved) AS deleted_now, -- 48210
(SELECT count(*) FROM orders
WHERE created_at < now() - interval '2 years') AS still_visible; -- 48210, the old snapshot

5Batching for Large Tables

For 48 thousand rows one statement is fine. For 400 million it is not. A single huge DELETE holds row locks on every deleted row until it commits, which blocks anyone updating those orders. It writes every deleted and inserted row to the write-ahead log, the WAL, which replicas must replay, so replication lag grows. And it leaves a huge number of dead rows that autovacuum must clean up at once.

So we move the rows in batches of, say, 10,000, each in its own short transaction, and repeat until a batch moves nothing. PostgreSQL's DELETE has no LIMIT clause, so we pick the batch with a subquery on the primary key.

SQL
WITH batch AS (
SELECT id FROM orders
WHERE created_at < now() - interval '2 years'
ORDER BY id
LIMIT 10000
FOR UPDATE SKIP LOCKED -- skip rows another session is changing right now
), moved AS (
DELETE FROM orders o USING batch b
WHERE o.id = b.id
RETURNING o.*
)
INSERT INTO orders_archive (id, customer_id, total, status, created_at)
SELECT id, customer_id, total, status, created_at FROM moved;
-- INSERT 0 10000 (repeat)
-- INSERT 0 10000
-- INSERT 0 3127
-- INSERT 0 0 (done)

The Java job simply runs this statement in a loop, committing after each run, and stops when the update count is zero. An index on created_at (or on (created_at, id)) keeps each batch selection cheap, and a short pause between batches gives replicas and autovacuum room to keep up. Because every batch is atomic on its own, the job can be stopped and restarted at any point without losing or duplicating rows.

6Surviving Schema Changes

INSERT INTO orders_archive SELECT * FROM moved matches columns by position, not by name. It works only while both tables have the same columns in the same order. The day someone adds a discount column to orders, the statement fails with a column count error, or worse, if the types happen to line up, it puts values into the wrong columns.

So in the batched version we listed the columns explicitly on both sides. When orders gains a column, the archive job keeps working, and we add the column to the archive deliberately. Two other things are worth checking before the first run: foreign keys that reference orders, such as order_items.order_id, will make the DELETE fail unless the child rows are archived first or in the same statement with another CTE, and any triggers on orders will fire for every deleted row.

7Follow-up questions

Can we archive the order items in the same statement?

Yes. We add another data-modifying CTE: WITH moved_orders AS (DELETE FROM orders ... RETURNING *), moved_items AS (DELETE FROM order_items i USING moved_orders m WHERE i.order_id = m.id RETURNING i.*), ins_items AS (INSERT INTO order_items_archive SELECT ... FROM moved_items) INSERT INTO orders_archive SELECT ... FROM moved_orders. The foreign key from order_items to orders must be checked at the end of the statement for this to work, which is the default for non-deferrable constraints in PostgreSQL; if it fails in your setup, delete the items in a first statement of the same transaction.

Would a partitioned table be better?

For time-based archiving at large scale, yes. If orders is partitioned by month, archiving a month becomes ALTER TABLE orders DETACH PARTITION orders_2023_05 and attaching it to the archive, which is a metadata change instead of moving millions of rows. The CTE approach is the right tool when the table is not partitioned or the archive rule is not purely time-based.

Does MySQL support this?

No. MySQL 8.4 does not allow DELETE or INSERT inside a CTE and has no RETURNING clause, so there we use a transaction with INSERT INTO archive SELECT ... WHERE id BETWEEN :a AND :b followed by DELETE FROM orders WHERE id BETWEEN :a AND :b, with a key range that is fixed before the batch starts.

8Conclusion

In this answer, we moved old orders to an archive with one statement: a DELETE ... RETURNING in a CTE feeding an INSERT. Because it is one statement in one snapshot, every row is either moved or not, and other sessions never see a half-moved state. Sub-statements can only see each other through RETURNING, large tables need batching through a key subquery to keep locks, WAL and vacuum under control, and explicit column lists keep the job working when the schema changes.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use a data-modifying CTE: WITH moved AS (DELETE FROM orders WHERE created_at < now() minus interval two years RETURNING star) INSERT INTO orders_archive SELECT from moved.

Then, if they want more

The rows inserted are exactly the rows deleted, because the insert reads only the RETURNING output, and since it is one statement in one transaction and one snapshot, a row is either still in orders or already in the archive. There is never a moment where it is in neither, and if the insert fails the delete rolls back.

One limit is that all sub-statements share the same snapshot, so they cannot see each other's changes to the tables except through RETURNING; a count of orders in the main query would still see the deleted rows.

On a large table I would not do it in one go, because it holds locks on every row, produces a lot of WAL and replica lag, and leaves a lot of dead tuples. I would batch it by choosing ten thousand ids in a subquery with LIMIT, delete those, insert them, commit, and loop until zero rows move.

And I would list the columns explicitly instead of SELECT star, so adding a column to orders does not break or corrupt the archive.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.4
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.
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 "Using a data-modifying CTE in PostgreSQL, move all orders older than two years from...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/1277e8fd9c/