How do I update a fields in table with strings randomly selected from a known list?
-
19-08-2019 - |
Question
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?
Solution
This might work for you:
BEGIN;
UPDATE Buildings SET Use = (ARRAY['warehouse', 'office', 'market', 'retail', 'workshop', NULL])[floor(random() * 6.0) + 1];
COMMIT;
OTHER TIPS
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.