Generating UUIDs with MySQL

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 it’s
own UUID generator baked in.

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

mysql> SELECT UUID

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
UPDATE, as 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
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.