Home » excel » mysql – Multiplying columns by randbetween in sql

mysql – Multiplying columns by randbetween in sql

Posted by: admin May 14, 2020 Leave a comment


I’ve got a table of real values that I’m trying to skew slightly for a demo table.

The table layout is effectively:


and I’m trying to multiply the right 3 columns by 85-115% so that the data still gives a reasonable representation of the original table, without giving away actual values.

In excel I’d do


for each column, but I’m trying to do the same with SQL, so that each row is multiplied by a different random number within the range.

I’m fairly new to sql, and I’m trying to avoid exporting the entire table, randomising the values in Excel and re-importing the table.

How to&Answers:

Use rand() with arithmetic:

select purchased * (0.85 + rand()*0.30)
from . . . 

This does what the question asks for, which is increasing or decreasing by about 15%. The code in Excel multiplies the value by about 100.


The update statement would be something like:

update table t
    set purchased = purchased * (0.85 + rand()*0.30)

As a final note: this doesn’t work exactly like the Excel version. One reason is that this uses continuous values rather than integer values.