Generating UUIDs with MySQL by Josh Sherman

0
15

Universally unique identifiers (UUID) are one of my favorite things. They are easy to generate, without collision, and they make it easy to expose an identifier to end users without it being so obviously guessable, like an automatically incrementing integer value.

While they are fantastic, the ability to generate one isn’t always baked into the programming language you’re using. For example, Node.js offloads this work to an external dependency.

While not the biggest deal in the world, if you happen to be using MySQL in your project, you may not need to include any additional dependencies. MySQL has its own UUID generator baked in.

To generate a UUID with MySQL, simply call the UUID() functions:

Which will spit back a string of letters and numbers that conform to UUID version 1 as defined in RFC 4122. It will look something like this:
aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee.

You can also use the UUID() function set a value on a table on INSERT or
UPDATEas such:

-- Adding a row with a UUID
mysql> INSERT INTO `myTable` (uniqueId) VALUES (UUID());

-- Updating a row with a UUID
mysql> UPDATE `myTable` SET uniqueId = UUID();

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here