Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random 10-digit ID number in PostgreSQL

I apologize if this has been answered elsewhere. I found similar posts but nothing that exactly matches what I was looking for. I am wondering if it is possible to randomly assign a number as data is entered into a table. For example, for this table

CREATE TABLE test (
id_number INTEGER NOT NULL,
second_number INTEGER NOT NULL)

I would like to be able to do the following:

INSERT INTO test (second_number)
VALUES (1234567)

where id_number is then populated with a random 10-digit number. I guess I want this similar to SERIAL in the way it populates but it needs to be 10 digits and random. Thanks very much

like image 610
quite_cool Avatar asked Oct 25 '25 02:10

quite_cool


1 Answers

You can try this expression:

CAST(1000000000 + floor(random() * 9000000000) AS bigint)

This will give you a random number between 1000000000 and 9999999999.

like image 198
Laurenz Albe Avatar answered Oct 27 '25 22:10

Laurenz Albe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!