Last active
July 21, 2025 08:16
-
-
Save julianjupiter/5ed5257e70f0c39a82d6a68849d06d72 to your computer and use it in GitHub Desktop.
Function to generate UUID version 7 in MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DELIMITER // | |
| CREATE FUNCTION uuidv7() RETURNS BINARY(16) | |
| DETERMINISTIC | |
| BEGIN | |
| DECLARE ts BIGINT; | |
| DECLARE uuid_bin BINARY(16); | |
| -- 1. Get current timestamp in milliseconds (UUIDv7 uses a 48-bit timestamp) | |
| SET ts = UNIX_TIMESTAMP(NOW(3)) * 1000; | |
| -- 2. Construct UUIDv7 binary format: timestamp + version + randomness | |
| SET uuid_bin = UNHEX(CONCAT( | |
| LPAD(HEX(ts), 12, '0'), -- 48-bit timestamp (6 bytes) | |
| '7', -- UUID version (v7) | |
| SUBSTR(HEX(RANDOM_BYTES(2)), 2), -- 12-bit randomness (2 bytes) | |
| HEX(FLOOR(RAND() * 4 + 8)), -- Variant (2 highest bits = 10xx) (1 byte) | |
| SUBSTR(HEX(RANDOM_BYTES(8)), 2) -- 64-bit randomness (8 bytes) | |
| )); | |
| RETURN uuid_bin; | |
| END // |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| select uuidv7() as id; | |
| select uuid_to_bin(bin_to_uuid(uuidv7())) as id; | |
| select bin_to_uuid(uuidv7()) as id; | |
| select bin_to_uuid(uuidv7()) as id; | |
| select bin_to_uuid(uuidv7()) as id; | |
| select bin_to_uuid(uuidv7()) as id; | |
| select bin_to_uuid(uuidv7()) as id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment