Skip to content
Advertisement

Evaluate random function for each row

I have the following sql:

This should generate a series of dates with an interval of one hour in it. What I now try to get is each day to be randomly fanned out. I have noticed that in the above sql statement random() is only evaluated once even though it is in a subquery.

Now without the CROSS JOIN I get:

and with the CROSS JOIN I now get for example:

What I would like to have is a random number each time I fan out. E.g.:

How do I need to modify my query to achieve that?

Advertisement

Answer

The problem is premature optimization. Postgres “forgets” that random() is volatile and should be called each time.

Here is a fix:

And a db<>fiddle.

Note that I made some substitutions that seem more “Postgres-like” — using now(), interval and so on for date arithmetic rather than converting strings.

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