Skip to content

Instantly share code, notes, and snippets.

@tzal
Last active September 8, 2023 07:32
Show Gist options
  • Save tzal/0a2ae8099ac419273e58 to your computer and use it in GitHub Desktop.
Save tzal/0a2ae8099ac419273e58 to your computer and use it in GitHub Desktop.
MySQL: convert GUID (UUID) to BINARY(16)
# MySQL: convert GUID (Microsoft-style UUID) to BINARY(16)
# '11223344-5566-7788-9900-AABBCCDDEEFF' → 0x44332211665588779900AABBCCDDEEFF
# Usage: CREATE TABLE example (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, guid BINARY(16) NOT NULL UNIQUE);
# INSERT INTO example (guid) VALUES (uuid_to_bin(UUID()));
# Tested on: MySQL 5.6, 5.7, 8.0
CREATE FUNCTION uuid_to_bin(s CHAR(36))
RETURNS binary(16)
DETERMINISTIC
RETURN UNHEX(CONCAT(
SUBSTRING(s,7,2), SUBSTRING(s,5,2), SUBSTRING(s,3,2), SUBSTRING(s,1,2),
SUBSTRING(s,12,2), SUBSTRING(s,10,2),
SUBSTRING(s,17,2), SUBSTRING(s,15,2),
SUBSTRING(s,20,4),
SUBSTRING(s,25,12)
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment