Generating UUIDs with MySQL

Josh Sherman
1 min read
Software Development SQL

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();
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

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

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles