Pick random values from an array in SQL(ite)

Python has a random.choice routine in the standard library that allows you to pick a random value from an iterable. It works like this: # src.py import random # The seed ensures that you'll get the same random choice # every time you run the script. random.seed(90) # This builds a list: ["choice_0", "choice_1", ..., "choice_9"] lst = [f"choice_{i}" for i in range(10)] print(random.choice(lst)) print(random.choice(lst)) This will print: choice_3 choice_1 I was looking for a way to quickly hydrate a table with random data in an SQLite database. To be able to do so, I needed to extract unpremeditated values from an array of predefined elements. The issue is, that SQLite doesn’t support array types or have a built-in function to pick random values from an array. However, recently I came across this1 trick from Ricardo Ander-Egg’s tweet2, where he exploits SQLite’s JSON support to parse an array. This idea can be further extended to pluck random values from an array. ...

September 2, 2022