Skip to content

Instantly share code, notes, and snippets.

@TyIsI
Forked from odan/mysq_uuid_v4.md
Last active November 29, 2023 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TyIsI/a8a1fdf7bd16c6901797e920c3bfbedb to your computer and use it in GitHub Desktop.
Save TyIsI/a8a1fdf7bd16c6901797e920c3bfbedb to your computer and use it in GitHub Desktop.
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;

As quick reference, here's the function implementation of the above:

CREATE FUNCTION `UUIDV4` () RETURNS VARCHAR(255) NOT DETERMINISTIC NO SQL SQL SECURITY INVOKER
RETURN 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))
    )
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment