Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a single UPDATE that sets products.price from a staging table price_updates(product_id, new_price) for only those rows, in PostgreSQL and in MySQL, and return the changed ids where possible.

In PostgreSQL we write UPDATE products p SET price = u.new_price FROM price_updates u WHERE p.id = u.product_id AND p.price IS DISTINCT FROM u.new_price RETURNING p.id, which updates only the matching rows and returns the changed ids. In MySQL we use a joined update, UPDATE products p JOIN price_updates u ON p.id = u.product_id SET p.price = u.new_price, and since MySQL has no RETURNING for UPDATE, we find the ids with a separate query. Skipping unchanged rows avoids useless row versions, trigger calls and log volume, duplicates in staging must be removed first because the engine would pick one arbitrarily, and large updates should run in batches.

Background to this question

Loading a file into a staging table and then applying it to the real table is a very common pattern: price lists, stock levels, exchange rates. The first version is often a Java loop that reads each staging row and runs one UPDATE per product, which takes an hour for a million rows. A single set-based UPDATE does the same work in seconds, but it has details that matter: which rows really change, what happens with duplicates, and how not to lock the table for minutes. In this answer, we will write the PostgreSQL version, then the MySQL version, see why filtering unchanged rows is worth it, handle duplicates in staging, and finally batch the update.

1A Quick Recap of Updating From Another Table

A plain UPDATE changes rows of one table, using values we write directly. Here the new values come from a second table, so the UPDATE must be joined with it: for each product row, find its row in price_updates and copy new_price into price. Products without a staging row must not be touched. SQL has no single standard spelling for this, so PostgreSQL and MySQL each have their own syntax, though the idea is identical.

Our tables are products(id, name, price numeric(12,2)) and price_updates(product_id, new_price numeric(12,2)), loaded with a few thousand rows from a supplier file.

2The PostgreSQL Version With RETURNING

PostgreSQL adds a FROM clause to UPDATE. Every row of products that finds a partner in price_updates through the WHERE condition is updated; the others are left alone, just as in an inner join.

SQL
UPDATE products p
SET price = u.new_price
FROM price_updates u
WHERE p.id = u.product_id
AND p.price IS DISTINCT FROM u.new_price -- skip rows whose price is already right
RETURNING p.id;
-- id
-- 1001
-- 1007
-- (2 rows) staging had 3 rows; product 1003 already had the new price

RETURNING gives back the ids of the rows actually changed, in the same statement, which is perfect for logging or for publishing price-changed events. Notice that we use IS DISTINCT FROM rather than <>. If a product's current price is NULL, p.price <> u.new_price is UNKNOWN and the row would be skipped, leaving the NULL in place. IS DISTINCT FROM treats NULL as a comparable value, so a NULL price that should become 9.99 is updated correctly.

3The MySQL Version

MySQL uses a multi-table UPDATE: the join goes directly after the UPDATE keyword, and SET comes after the join.

SQL
UPDATE products p
JOIN price_updates u ON p.id = u.product_id
SET p.price = u.new_price
WHERE NOT (p.price <=> u.new_price); -- null-safe "is different"
-- Query OK, 2 rows affected
-- No RETURNING for UPDATE in MySQL: find the ids separately, before or in the same transaction
SELECT p.id FROM products p JOIN price_updates u ON p.id = u.product_id
WHERE NOT (p.price <=> u.new_price);

MySQL 8.4 has no RETURNING clause for UPDATE, so if we need the ids, we select them first inside the same transaction, using SELECT ... FOR UPDATE to lock those rows so nothing changes between the two statements. The <=> operator is MySQL's null-safe equality, so NOT (a <=> b) plays the role of IS DISTINCT FROM. Also note that by default MySQL reports rows changed, not rows matched, in its affected-rows count, while Connector/J reports matched rows unless useAffectedRows=true is set; check your driver settings before relying on the count.

4Why Filtering Unchanged Rows Matters

It is tempting to skip the IS DISTINCT FROM filter, since setting a price to the value it already has looks harmless. It is not free. In PostgreSQL, every updated row gets a new row version, even if no value changed, which writes to the table and possibly its indexes, adds to the write-ahead log (WAL), and leaves a dead version for vacuum to clean up. Update triggers fire, audit tables grow, CDC streams such as Debezium emit change events that every consumer processes, and replicas must replay all of it.

Updating 100,000 staged rows, of which 3,000 changed
VersionRows writtenSide effects
Without the filter100,000100,000 row versions, trigger calls and CDC events
With IS DISTINCT FROM3,000only real price changes reach logs and consumers
Supplier files usually repeat most prices, so the filter removes most of the work.

5Handling Duplicate Rows in Staging

Suppose the supplier file lists product 1001 twice, once with 9.99 and once with 10.49. In PostgreSQL's UPDATE ... FROM, a target row that joins to several source rows is updated only once, using one of them, and which one is not predictable. MySQL behaves similarly. So the result depends on the plan, and nobody gets an error.

SQL
-- Find duplicates before applying
SELECT product_id, count(*) FROM price_updates GROUP BY product_id HAVING count(*) > 1;
-- 1001 | 2
-- Prevent them for the future
ALTER TABLE price_updates ADD PRIMARY KEY (product_id);
-- Or deduplicate with an explicit rule, for example the last loaded row wins
DELETE FROM price_updates a USING price_updates b
WHERE a.product_id = b.product_id AND a.loaded_at < b.loaded_at;

The best fix is a primary key or unique constraint on price_updates.product_id, so the load fails loudly when the file has duplicates. If duplicates are legitimate, for example several updates during the day, we choose a rule, such as latest wins, and apply it before the UPDATE.

6Batching Large Updates

For a few thousand rows, one statement is perfect. For a few million, a single UPDATE holds row locks on every changed product until it commits, which can block checkout transactions that read prices with FOR UPDATE, and it produces one huge burst of WAL or binlog that replicas replay serially, causing replication lag. So we split the work into batches of about 10,000 rows, each in its own short transaction.

SQL
-- PostgreSQL: one batch, repeated until it updates 0 rows
WITH batch AS (
SELECT u.product_id, u.new_price
FROM price_updates u JOIN products p ON p.id = u.product_id
WHERE p.price IS DISTINCT FROM u.new_price
ORDER BY u.product_id
LIMIT 10000
)
UPDATE products p SET price = b.new_price
FROM batch b WHERE p.id = b.product_id
RETURNING p.id;
-- 10000 rows, then 10000, ..., then 0: done

Each batch picks up rows that still need changing, so the loop stops by itself and can be restarted safely after a failure. Ordering by product_id makes concurrent batches lock rows in the same order, which avoids deadlocks. In MySQL, a multi-table UPDATE cannot use LIMIT, so we batch by key ranges instead, for example WHERE p.id BETWEEN 1 AND 10000, then the next range. From Spring, each batch runs in its own transaction, for example through a TransactionTemplate in a loop, with a short sleep between batches if replicas fall behind.

7Follow-up questions

How would you do this in batches of 10,000?

In PostgreSQL I would use a CTE that selects up to 10,000 staging rows whose price still differs, ordered by product_id, and an UPDATE ... FROM that CTE, running it in a loop where each iteration is its own transaction until it updates zero rows. Because the filter only picks rows that still need changing, the loop is restartable. In MySQL I would loop over product id ranges, say 10,000 ids at a time, because multi-table UPDATE does not accept LIMIT. Between batches I would check replication lag and pause if it grows.

Why not do it in Java with saveAll()?

Loading a million entities, changing them and flushing them sends a million separate UPDATE statements, even with JDBC batching, and keeps all the entities in the persistence context. A single set-based statement lets the database do the join and the update in one pass, usually hundreds of times faster. I would run it as a native query or with JdbcTemplate.

8Conclusion

In this answer, we wrote the joined update in PostgreSQL with UPDATE ... FROM and RETURNING, and in MySQL with a multi-table UPDATE and a separate SELECT for the ids, because MySQL has no RETURNING for UPDATE. We filtered out unchanged rows with IS DISTINCT FROM or NOT (a <=> b) to avoid useless row versions, triggers and log volume, made staging unique so the engine never picks an arbitrary duplicate, and batched large updates in short transactions.

What to say in the interviewAbout 70 seconds aloud

Open with

In PostgreSQL I'd write UPDATE products p SET price = u.new_price FROM price_updates u WHERE p.id = u.product_id AND p.price IS DISTINCT FROM u.new_price RETURNING p.id. Only products with a staging row are touched, and RETURNING gives me the ids that actually changed.

Then, if they want more

In MySQL the syntax is UPDATE products p JOIN price_updates u ON p.id = u.product_id SET p.price = u.new_price, with NOT p.price <=> u.new_price as the null-safe filter; MySQL has no RETURNING for UPDATE, so I'd select the ids first in the same transaction with FOR UPDATE.

Filtering out unchanged rows is important, because otherwise every row gets a new version, triggers fire, and WAL or binlog and CDC events are produced for nothing. IS DISTINCT FROM rather than not-equal also handles NULL prices.

If staging has duplicate product ids, the engine silently picks one row arbitrarily, so I'd put a primary key on price_updates.product_id or deduplicate with an explicit rule first. For millions of rows I'd batch it, 10,000 at a time in separate transactions, ordered by product id, which limits lock time and replication lag and can be restarted safely.

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 "Write a single UPDATE that sets products.price from a staging table...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/62d9f917bc/