views:

132

answers:

2

I have a table named "buildings" that contains a varchar(50) field named "use". The table already has several thousand records, however the "use" values are all null. I would like to update these this table with randomly chosen values from a list of strings (e.g., warehouse, office, market, retail, workshop). I would also like to leave some of these null to emulate real world usage.

How can I update a field in a table with strings randomly selected from a known list?

A: 

It's not random, but this is a nice and easy way to do it, provided you have a realtively uniform distribution of IDs:

UPDATE Buildings SET Use = 'warehouse' WHERE ID % 6 = 0
UPDATE Buildings SET Use = 'office'    WHERE ID % 6 = 1
UPDATE Buildings SET Use = 'market'    WHERE ID % 6 = 2
UPDATE Buildings SET Use = 'retail'    WHERE ID % 6 = 3
UPDATE Buildings SET Use = 'workshop'  WHERE ID % 6 = 4
UPDATE Buildings SET Use = NULL        WHERE ID % 6 = 5

This is almost certainly going to be easier and faster than a "random" approach. Then again, it might not be random enough.

Michael Haren
+2  A: 

This might work for you:

BEGIN;
UPDATE Buildings SET Use = (ARRAY['warehouse', 'office', 'market', 'retail', 'workshop', NULL])[floor(random() * 6.0) + 1];
COMMIT;
calebbrown
Could also populate a table with the choices, especially if there are many choices.
Jørn Jensen