Similar to my previous post, this code generates a UUID of the new v7 type, which has a Unix-timestamp base. This keeps UUIDs sortable by creation-date, which is useful when using them as database keys, for example
SELECT LOWER(CONCAT(
INSERT(LPAD(HEX(UNIX_TIMESTAMP() * 1000 + FLOOR(MICROSECOND(NOW(6)) / 1000)), 12, '0'), 9, 0, '-'),
'-7',
LPAD(HEX(FLOOR(RAND() * 0x1000)), 3, '0'),
'-',
HEX(0x8000 | FLOOR(RAND() * 0x4000)),
'-',
LPAD(HEX(FLOOR(RAND() * 0x1000000000000)), 12, '0')
)) AS uuidv7;
You can either use this inline in your select statement, or convert it to a function.