Random
Another tip from Haki Benita. While it is possible to do this in say Python, it can be useful to do everything in SQL.
Random
To generate random numbers PostgreSQL provides a random function that returns a value between 0 and 1:
| |
To generate values at different ranges you can random in an expression:
| |
It’s a common mistake to use round instead of ceil or floor to generate a range of integers. Using round may produce inconsistent distribution. Consider the following query to generate random integers in the range 0 - 4 using round instead ceil:
| |
Notice how the values 0 and 3 are coming up less than 1 and 2. Using round, random values less than 0.5 will be rounded down to 0, and random numbers greater than 2.5 will be rounded up to 3, while for example, random values between 0.5 and 1.5 will be rounded to 1. This makes the edges less likely to come up.
This problem can be solved by either rounding up or down. Consider the same query using ceil:
| |
Using ceil produces more evenly distributed random numbers.
Random Choice
You can use the random function to pick a random value from a list of values:
| |
The expression defines an array of colors, and then uses random to get a random element from the array. Notice that in PostgreSQL, arrays start at 1:
| |
#Sql #Postgresql #Random #Generate_series #Ceil #Array #Haki Benita