Skip to content
Advertisement

Why can’t I use SELECT … FOR UPDATE with aggregate functions?

I have an application where I find a sum() of a database column for a set of records and later use that sum in a separate query, similar to the following (made up tables, but the idea is the same):

However, in theory someone could update the cost column on the materials table between the two queries, in which case the calculated percents will be off.

Ideally, I would just use a FOR UPDATE clause on the first query, but when I try that, I get an error:

Now, the work-around isn’t the problem – just do an extra query to lock the rows before finding the Sum(), but that query would serve no other purpose than locking the tables. While this particular example is not time consuming, the extra query could cause a performance hit in certain situations, and it’s not as clean, so I’d like to avoid having to do that.

Does anyone know of a particular reason why this is not allowed? In my head, the FOR UPDATE clause should just lock the rows that match the WHERE clause – I don’t see why it matters what we are doing with those rows.

EDIT: It looks like SELECT … FOR UPDATE can be used with analytic functions, as suggested by David Aldridge below. Here’s the test script I used to prove this works.

Which gives the output:

Advertisement

Answer

The syntax select . . . for update locks records in a table to prepare for an update. When you do an aggregation, the result set no longer refers to the original rows.

In other words, there are no records in the database to update. There is just a temporary result set.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement