UUIDv4 in MySQL

Although MySQL has a UUID() function, it returns a version 1 UUID, which is time-based and has mostly been replaced by the completely random version 4.

I recently needed a v4 in a query, and adapted this from some different options I found online:

SELECT LOWER(CONCAT(
	LPAD(HEX(FLOOR(RAND() * 0x100000000)), 8, '0'),
	'-',
	LPAD(HEX(FLOOR(RAND() * 0x10000)), 4, '0'),
	'-4',
	LPAD(HEX(FLOOR(RAND() * 0x1000)), 3, '0'),
	'-',
	HEX(0x8000 | FLOOR(RAND() * 0x4000)),
	'-',
	LPAD(HEX(FLOOR(RAND() * 0x1000000000000)), 12, '0')
)) AS uuidv4;

You can either use this inline in your select statement, or convert it to a function.

Comments are disabled for this post