How to generate a unique and random number for a primary key in sql

纵饮孤独 提交于 2019-12-13 03:33:34

问题


I am working on a requirement where I need to generate a unique(non-repeatable) and random number(unpredictable) with atleast 10 digits. I tried SELECT FLOOR(RAND() * 9999999).. but the uniqueness cant be guaranteed with this. About 20k values will be inserted per month approx.

Also I want to increment an int column of my table(number_of_hits) for every entry inserted... I am using spring boot to insert values into table. Tried number_of_hits int AUTO_INCREMENT while creating the table but later got to know this will only work on primary key.. Thanks in advance.!


回答1:


The easiest solution is to use a UUID datatype (which can be populated automatically), and convert to INT when you need it.

A UUID is a 128-bit integer and can be converted to BigInteger; it's usually stored as a hexadecimal value, which may appear to be a string.




回答2:


Use newid() function.This will creates a unique value of type uniqueidentifier.

NEWID()
SELECT NEWID()

You can use like this.

INSERT INTO mytable (column1) VALUES (NEWID())



回答3:


I have gone with the below solution and it works fine with millions of records too.. Thank you all for your answers.

      Calendar cal = Calendar.getInstance();
      long currentTime = cal.getTimeInMillis();
      long Max = 9999999999999L;
      long Min = 1000000000000L;
    long range = Math.abs((long) (Math.random() * (Max - Min)) + Min);
    long id = Math.addExact(currentTime, range);
    String uniqueID = createUniqueID(id);
    boolean isRepeated = urlShortenerRepository.existsByShortUrlKey(uniqueID);
    while (isRepeated) {
        range = Math.abs((long) (Math.random() * (Max - Min)) + Min);
        id = Math.addExact(currentTime, range);
        uniqueID = createUniqueID(id);
        isRepeated = urlShortenerRepository.existsByShortUrlKey(uniqueID);
    }



回答4:


Since you have chosen to use Java code to generate a unique identifier, I want to say that you should generate a unique identifier that combines a "unique" part and a "random" part. Note that your current answer doesn't exactly meet the "unpredictable" requirement, since it uses Math.random(), which is not necessarily an "unpredictable" RNG.

  • The "unique" part can be a monotonically increasing counter, or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating). I don't recommend timestamps alone since the risk exists of generating the same timestamp in rapid succession.
  • The "random" part is simply a random number generated with a cryptographic random number generator (which for Java is java.security.SecureRandom; use the "DRBG" implementation rather than "SHA1PRNG" if available). In general, the longer the random part is, the less predictable it will be.

Your current code is on the right track, but you should concatenate the two parts of the random ID (like they were strings) rather than adding an arbitrary offset to the current time (e.g., what if cal.getTimeInMillis() returns a number greater than Min?).



来源:https://stackoverflow.com/questions/51167523/how-to-generate-a-unique-and-random-number-for-a-primary-key-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!