MySQL UUID Generator

Generate a UUID instantly, then copy ready-to-use MySQL SQL for generating and efficiently storing UUIDs.

Generate a UUID in MySQL

UUID() - built-in function (version 1)

SELECT UUID();
-- e.g. 3fa85f64-5717-4562-b3fc-2c963f66afa6

MySQL's native UUID() generates a time-based version-1 UUID using the server's MAC address and current timestamp.

Storing UUIDs efficiently as BINARY(16)

Storing UUIDs as a 36-character string wastes space and slows down indexes. Use UUID_TO_BIN() / BIN_TO_UUID() (MySQL 8.0+) to store them as 16 bytes instead.

CREATE TABLE orders (
    id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)),
    customer_name VARCHAR(255)
);

INSERT INTO orders (customer_name) VALUES ('Jane Doe');

SELECT BIN_TO_UUID(id, 1) AS id, customer_name FROM orders;

The second argument 1 swaps the time-low and time-high fields so values sort chronologically, which keeps the clustered index (InnoDB primary key) append-only and avoids fragmentation.

Generating a UUID in application code instead

INSERT INTO orders (id, customer_name)
VALUES (UUID_TO_BIN('3fa85f64-5717-4562-b3fc-2c963f66afa6', 1), 'Jane Doe');

Generating UUID v7 values in your application (see Node.js, PHP, Python) and inserting them gives the same sortable-index benefit as UUID_TO_BIN(UUID(), 1) while remaining portable to other databases.