Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

This query fails in PostgreSQL with 'FOR UPDATE is not allowed with GROUP BY clause':

SQL
SELECT customer_id, sum(amount)
FROM invoice
WHERE status = 'OPEN'
GROUP BY customer_id
FOR UPDATE;

Also, a version with a LEFT JOIN to an optional table fails. Explain the rules and how to rewrite.

A row lock belongs to one physical row of one table, and a grouped, aggregated, DISTINCT or UNION result row does not correspond to any single table row, so PostgreSQL refuses FOR UPDATE there. We rewrite the query to lock the base invoice rows first, in a subquery or CTE, and aggregate the locked rows afterwards. With a LEFT JOIN, the nullable side may have no row to lock, so we name the tables to lock with FOR UPDATE OF invoice.

Why this question is asked

This error looks like a syntax quirk, but it comes from what a row lock really is, and the rewrite teaches us to think about which rows we actually need to protect. Interviewers ask it to see whether we can explain the rule instead of memorising it, and whether we notice that locking every open invoice to compute a sum may be a bad idea in the first place. In this answer, we will recap what FOR UPDATE locks, see why grouped results cannot be locked, rewrite the query, handle the outer join case with FOR UPDATE OF, and then ask whether the lock is needed at all.

1A Quick Recap of What FOR UPDATE Locks

SELECT ... FOR UPDATE tells PostgreSQL to lock every row the query returns, so that no other transaction can update or delete those rows until our transaction ends. PostgreSQL stores the lock in the row itself, in the header of the specific row version on disk. So for each output row, it must be able to point at exactly one row in a table and mark it.

For a simple query that is easy: each result row is one invoice row. For a join without FOR UPDATE OF, each result row combines one row from each table, and PostgreSQL locks all of them.

2Why GROUP BY Cannot Be Locked

A grouped result row is computed from many table rows. The row (customer 7, sum 1,250.00) might come from 14 invoices. There is no single row to mark, and PostgreSQL does not try to guess that we meant all 14. The same applies to aggregates without GROUP BY, DISTINCT, HAVING, window functions and set operations such as UNION, which all produce rows that are not table rows.

SQL
SELECT customer_id, sum(amount) FROM invoice
WHERE status = 'OPEN' GROUP BY customer_id FOR UPDATE;
-- ERROR: FOR UPDATE is not allowed with GROUP BY clause
SELECT DISTINCT customer_id FROM invoice WHERE status = 'OPEN' FOR UPDATE;
-- ERROR: FOR UPDATE is not allowed with DISTINCT clause

The exact wording differs slightly by construct and version, but the reason is always the same: the rows we would lock do not exist as table rows.

3The Rewrite: Lock the Rows, Then Aggregate

The fix is to split the work into the two things we want. First lock the base rows, which is a plain query over invoice and can carry FOR UPDATE. Then aggregate the locked rows in an outer query. A CTE (a WITH clause) reads well for this.

SQL
WITH locked AS (
SELECT id, customer_id, amount
FROM invoice
WHERE status = 'OPEN'
ORDER BY id -- consistent lock order reduces deadlocks
FOR UPDATE
)
SELECT customer_id, sum(amount) AS open_total
FROM locked
GROUP BY customer_id;
-- customer_id | open_total
-- 7 | 1250.00
-- 12 | 310.50
Step throughLocking base rows before aggregating
  1. Select base rowsplain query over invoice: each result row is one table row
  2. Lock themFOR UPDATE, ordered by id
  3. Aggregate in the outer queryGROUP BY over the locked rows
  4. Use the totalsthe rows behind them cannot change until commit

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

Notice the ORDER BY id inside the locking query. Locks are taken as rows are returned, so two sessions running this query would otherwise lock rows in whatever order the plan produces, and could deadlock. Locking in primary key order makes every session queue behind the first one instead. An equivalent form puts the locking query in a subquery in FROM, or locks with WHERE id IN (SELECT id ... FOR UPDATE) and aggregates in the outer query.

4The LEFT JOIN Case and FOR UPDATE OF

Now suppose we join an optional table, for example a discount that may or may not exist for each invoice. With a LEFT JOIN, invoices without a discount produce result rows where every discount column is null. There is no discount row to lock, so PostgreSQL refuses.

SQL
SELECT i.id, i.amount, d.percent
FROM invoice i LEFT JOIN discount d ON d.invoice_id = i.id
WHERE i.status = 'OPEN'
FOR UPDATE;
-- ERROR: FOR UPDATE cannot be applied to the nullable side of an outer join
SELECT i.id, i.amount, d.percent
FROM invoice i LEFT JOIN discount d ON d.invoice_id = i.id
WHERE i.status = 'OPEN'
FOR UPDATE OF i; -- lock only invoice rows
-- returns all open invoices; discount rows are read but not locked

FOR UPDATE OF names the tables (by alias) whose rows should be locked, and leaves the others unlocked. That is often what we want anyway: we protect the invoices we will update and only read the discounts. If we really need the discount rows locked too, we lock them in a separate statement where they are not on the nullable side.

5Do We Need the Lock at All?

The rewrite works, but locking every open invoice to compute totals can serialise a lot of unrelated work. Every invoice update, payment and cancellation for those customers now waits until our transaction ends, and if the totals feed a long report, that might be seconds or minutes.

So it is worth asking what the lock protects. If we only display totals, a plain SELECT on a snapshot is enough and takes no locks. If we compute totals to make a decision, such as blocking customers over a credit limit, it may be enough to lock one row per customer, for example the customer row, and make every invoice change take that same lock, which is far fewer locks. Or we can let the decision run at REPEATABLE READ or SERIALIZABLE and retry on conflict. Locking the base rows is right when we will change exactly those rows in the same short transaction.

6Follow-up questions

Does FOR UPDATE inside a CTE always lock all the rows it selects?

It locks the rows that the locking query actually returns as the outer query reads them. If the outer query does not read all of them, for example because of a LIMIT in the outer query, some rows may not be locked. Keep the LIMIT inside the locking query and let the outer query read the CTE fully.

Can we use FOR UPDATE SKIP LOCKED in the same rewrite?

Yes. Adding SKIP LOCKED to the inner locking query makes it skip invoices locked by others, which is useful for queue-like work, but then the totals only cover the rows we managed to lock, so it is wrong for computing accurate sums.

What about MySQL?

MySQL is more permissive in some cases but the idea is the same: locks are on index records of base tables, so the reliable pattern is to lock base rows with a plain SELECT ... FOR UPDATE and aggregate separately. MySQL 8 also supports FOR UPDATE OF with table names.

7Conclusion

In this answer, we saw that FOR UPDATE marks specific table rows, so it cannot apply to grouped, aggregated, DISTINCT or set-operation results, and it cannot lock the nullable side of an outer join where no row may exist. We lock the base rows first in a CTE or subquery, in id order, and aggregate afterwards, and use FOR UPDATE OF to lock only the tables we need. Finally, we question whether locking many rows to compute a sum is needed, because it can serialise other work.

What to say in the interviewAbout 80 seconds aloud

Open with

A row lock in PostgreSQL is a mark on a specific row version of a specific table, so every output row of a FOR UPDATE query has to map to exactly one table row.

Then, if they want more

A GROUP BY result like customer 7 with a sum is built from many invoices, and the same goes for aggregates, DISTINCT and UNION, so PostgreSQL refuses.

I'd rewrite it as a CTE or subquery that selects the invoice rows with status OPEN, ordered by id so sessions lock in the same order, with FOR UPDATE, and then group and sum the locked rows in the outer query.

For the LEFT JOIN version, the optional table's columns are null for invoices without a match, so there's no row to lock on that side. I'd use FOR UPDATE OF with the invoice alias to lock only the invoices and just read the other table.

Then I'd ask whether we need the lock at all, because locking every open invoice to compute totals blocks every payment and update on them. For display a plain snapshot read is enough, and for a decision a lock on one row per customer, or a retry at a stronger isolation level, may be cheaper.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8
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 "This query fails in PostgreSQL with 'FOR UPDATE is not allowed with GROUP BY clause':": https://scrivio-interview-library.netlify.app/databases/database-locking/f439a3f4bb/