Skip to content

Instantly share code, notes, and snippets.

@odan
Last active January 25, 2023 04:13
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Generating UUID v4 in MySQL

Generating UUID v4 in MySQL

SELECT
  LOWER(
    CONCAT(
      # 1th and 2nd block are made of 6 random bytes
      HEX(RANDOM_BYTES(4)),
      '-',
      HEX(RANDOM_BYTES(2)),
      # 3th block will start with a 4 indicating the version, remaining is random
      '-4',
      SUBSTR(HEX(RANDOM_BYTES(2)), 2, 3),
      '-',
      # 4th block first nibble can only be 8, 9 A or B, remaining is random
      CONCAT(
        HEX(FLOOR(ASCII(RANDOM_BYTES(1)) / 64) + 8),
        SUBSTR(HEX(RANDOM_BYTES(2)), 2, 3)
      ),
      '-',
      # 5th block is made of 6 random bytes
      HEX(RANDOM_BYTES(6))
    )
  ) AS UUID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment