Geekery

Working with the random() function in PostgreSQL can be a bit tricky if you’re trying to populate a table.

The random() function in PostgreSQL will return a number between 0 and 1 like so:

SELECT RANDOM();
      random       
-------------------
 0.115072432027698
(1 ROW)

If you’re trying to get a whole number from random(), you can use some multiplication and the round() function to let random() work for you. Say you wanted to get a random number from 0-100:

SELECT ROUND(RANDOM() * 100);
 round 
-------
    22
(1 ROW)

For the project I’m working on, we wanted to pre-populate some birthdays with random dates. I tried using a combination of the datetime functions with an interval and random() and couldn’t quite get there. Searching around on Google didn’t provide too many useful results so I turned to the wonderful folks in the #postgresql chat at irc.freednode.net. Using a combination of the above and the suggestions from the chat room, I was able to come up with a query that did what I wanted:

SELECT NOW() - '1 year'::INTERVAL * ROUND(RANDOM() * 100);
           ?COLUMN?           
------------------------------
 1987-01-20 11:10:34.26494-07
(1 ROW)

That means we could easily update our tables for people with random birthdays with a single update query:

UPDATE TABLE_NAME SET birthday = NOW() - '1 year'::INTERVAL * ROUND(RANDOM() * 100);

Hopefully you found this post useful. If you did, please consider subscribing to my feed.

  • luis dominguez

    Buenos dias, estoy en estos momentos en un proceso de migracion de una base de datos de un manejador ms sql server 7.0 a postgresql vesion 8.4 pero tengo un problema con un tipo de dato el (timestamp) que en sql server 7.0 se refiere a un campo binario unico que se actualiza en forma aleatoria por fila , y este campo es primordial en mi aplicacion para efectos del seguimiento, ahora en postgresql 8.4 tambien tengo el mismo timestamp pero se refiere a otro tipo de dato (fecha+hora ), he investigado otros tipo de datos tales como (serial, uuid,xid, bytea etc) y no consigo algo igual para sustituirlo, he pensado en una funcion que realice algo parecido pero todavia no lo intento.

    Saludos
    Luis Dominguez

  • Andrea

    Cool post XD
    you saved me some time of research =P
    Thumbs up! (y)

  • Kumar

    Kewlness, you saved my time.

  • Ilya

    Drake, this is very helpful. Many Thanks.