Skip to content
Advertisement

Oracle database – update table with random value from literal table, but change data per row

I want to randomly pick a data tuple from a literal table to fill in another table, and randomize the row to pick each time. With the below query, I fill all rows with the same data, so I think the random row is picked once and used everywhere.

So how can I get a random row for each row to update in the Oracle database?

Advertisement

Answer

As per my similar answer to another question on picking random rows, you can do it but you need to add some seemingly irrelevant filters to force the SQL optimiser to not materialize the sub-query and to ensure the values are randomly generated for each row:

Which, for the sample data:

Then after the MERGE, the table may (randomly) contain:

ORGANIZATION_ID COMPANY_ID CODE
3.44.5 33333333 1234567
3.11 11111111 1234567
3.44.5 33333333 1234567
3.22.3 22222222 1234567
3.11 11111111 1234567

db<>fiddle here

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