MySQL UUID() when not unique?

ina picture ina · Mar 13, 2012 · Viewed 9.1k times · Source

What happens when a UUID() generated by MySQL is not unique? If this is for a column that is a primary key, does MySQL error out, or does it try generating another UUID until a truly unique one is found?

Answer

Nanne picture Nanne · Mar 13, 2012

Well, if you call UUID() twice and get the same results, the most problematic thing would be that "stuff is broken" (tm). It's supposed to be unique and it should be always, as far as I know.

There would be no "regenerate" code available: the function is designed to create unique keys even across computers, so how could it even know its result was not unique?

from http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other.

Maybe you mean something else? For instance, if you use UUID() to generate somethingthat should be unique (like a primary key, or a Unique field etc), and you've previously added the same number (like for instance you called UUID() once, but inserted something twice), then you'll just get the default error you get when adding non-unique content to a place that should be unique. You will not get a new one.

some reading material about the uniqueness:

  1. the manual. Read it, and how it uses various parts to generate the uuid.: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

  2. Check the link on that manual for the actual definition (but that's quite a read, so you might skip this one): https://www2.opengroup.org/ogsys/jsp/publications/PublicationDetails.jsp?catalogno=c706

  3. Some easier to understand metrics on probability of dubplicates here: http://en.wikipedia.org/wiki/Universally_unique_identifier

  4. there is some talk on the mysql site (forums etc) too, about using it as primary key, but as i'm at work and short on time, you need to search for that yourself :)