Generating random numbers is a surprisingly common task in programs, whether it's to create test data or to provide a user with a random entry from a list of items.

PostgreSQL comes with just a few simple foundational functions that can be used to fulfill most needs for randomness.

Almost all your random-ness needs will be met with the `random()`

function.

##
Uniformity

The `random()`

function returns a double precision float in a continuous uniform distribution between 0.0 and 1.0.

What does that mean? It means that you could get any value between 0.0 and 1.0, with equal probability, for each call of `random()`

.

Here's five uniform random numbers between 0.0 and 1.0.

```
SELECT random() FROM generate_series(1, 5)
```

```
0.3978842227698167
0.7438732417540841
0.3875091442400458
0.4108009373061563
0.5524543763568912
```

Yep, those look pretty random! But, maybe not so useful?

##
Random Numbers

Most times when people are trying to generate random numbers, they are looking for random **integers** in a range, not random floats between 0.0 and 1.0.

Say you wanted random integers between 1 and 10, inclusive. How do you get that, starting from `random()`

?

Start by scaling an ordinary `random()`

number up be a factor of 10! Now you have a continuous distribution between 0 and 10.

```
SELECT 10 * random() FROM generate_series(1, 5)
```

```
3.978842227698167
7.438732417540841
3.875091442400458
4.108009373061563
5.5245437635689125
```

Then, if you push every one of those numbers up to the nearest integer using `ceil()`

you'll end up with a random integer between 1 and 10.

```
SELECT ceil(10 * random()) FROM generate_series(1, 5)
```

```
4
8
4
5
6
```

If you wanted a random integer between 0 and 9, you could do the same thing, but pushing the floating numbers **down** to the next lowest integer using `floor()`

.

```
SELECT floor(10 * random()) FROM generate_series(1, 5)
```

```
3
7
3
4
5
```

##
Random Rows and Values

Sometimes the things you are trying to do randomly aren't numbers. How do you get a random entry out of a string?

[...]