I am trying to generate random serial numbers in PostgreSQL with some conditions.
- The numbers need to start with the same 3 letters, YAK.
- After YAK, there needs to be 8 random digits.
- I only need to do 10 iterations of this.
I know I should try to start with generate_series() but can I use RANDOM() in there at all like I probably would for python?
2
Answers
You seem to have all the building blocks, you just need to put them together:
generate_series
can be used in thefrom
clause to generate 10 rowsrandom
and multiply it by 100,000,000 to generate a random number between 0 and 99,999,999.SQLFiddle demo
You can implement a function to randomize, like
Parameters:
Explanation: You select a randomized number based on pool size, LPAD resolves the character length and you concatenate the result to the prefix.
Fiddle: https://sqlfiddle.com/postgresql/online-compiler?id=20edf888-8258-418c-9ba3-31c22dcc30e7