4

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?

2 Answers 2

8

This might work for you:

BEGIN;
UPDATE Buildings SET Use = (ARRAY['warehouse', 'office', 'market', 'retail', 'workshop', NULL])[floor(random() * 6.0) + 1];
COMMIT;
3
  • Could also populate a table with the choices, especially if there are many choices. Jan 16, 2009 at 7:42
  • @JørnJensen can you explain what you are saying Jul 11, 2017 at 10:31
  • BTW this is perfect. Work like a charm! Jul 11, 2017 at 10:37
0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.