1

Consider this:

UPDATE dest
SET dest_col = (SELECT s.src_col FROM source s
                WHERE s.name = 'abc'
                ORDER BY random() LIMIT 1 OFFSET 0);

My goal: Set dest.dest_col in every row to a randomly picked value out of all the values matched by the subquery.

To accomplish that, I added ORDER BY random() LIMIT 1. But this works by picking a random value once, and then setting it to every row in the dest.dest_col.

I tried adding OFFSET 0 (suggested in other answers as a way to prevent Postgres from optimizing the subquery), but this doesn't seem to have any effect.

Also note that I need this to work on PostgreSQL running on GCP.

1

The subquery is evaluated only once because it has no dependency on the row to update.

You may add one, just to force the engine to evaluate the subquery for each row. For instance if dest_col is a non-null number:

UPDATE dest
SET dest_col = (SELECT s.src_col FROM source s
                WHERE s.name = 'abc'
                ORDER BY random()+dest_col LIMIT 1)

Or if it's not a number, any other column that is a number in dest will do, or any other expression involving column(s) of the table to update that will not affect the result but create a dependency.

  • Worked like a charm. And explained briefly yet clearly. Cheers! – kamituel Aug 23 '18 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.