MySQL provides a UUID() function that returns a version 1 (time-based) UUID as a 36-character string. For storage efficiency, MySQL 8 adds UUID_TO_BIN() and BIN_TO_UUID() to convert between the text form and a compact 16-byte representation.
The examples below cover generating a UUID and storing it the recommended way.
Generate a UUID string
Call UUID() in any statement to get a new identifier as text.
SELECT UUID();
-- 3f47a0e2-9c0b-11ee-8f3b-0242ac120002Store UUIDs as BINARY(16)
Storing the 36-character text wastes space and slows indexes. Use BINARY(16) and convert with UUID_TO_BIN()/BIN_TO_UUID(). The optional second argument to UUID_TO_BIN reorders time fields for better index locality.
CREATE TABLE users (
id BINARY(16) PRIMARY KEY,
email VARCHAR(255) NOT NULL
);
INSERT INTO users (id, email)
VALUES (UUID_TO_BIN(UUID(), 1), 'a@example.com');
SELECT BIN_TO_UUID(id, 1) AS id, email FROM users;Frequently asked questions
- What UUID version does MySQL UUID() return?
- UUID() returns a version 1, time-based UUID as a 36-character string.
- Should I store MySQL UUIDs as CHAR(36) or BINARY(16)?
- BINARY(16) is recommended. It halves storage versus CHAR(36) and, with UUID_TO_BIN(uuid, 1), improves index performance.
- What does the second argument to UUID_TO_BIN do?
- Passing 1 swaps the time-low and time-high fields so sequential UUIDs sort better, improving primary-key index locality.
