Skip to content

Instantly share code, notes, and snippets.

@emptyother
Forked from tzal/uuid_to_bin.sql
Created August 21, 2020 09:23
Show Gist options
  • Save emptyother/f5d67c25798c050fa0598a58b1f2631b to your computer and use it in GitHub Desktop.
Save emptyother/f5d67c25798c050fa0598a58b1f2631b 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()));
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