Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format uuid string from binary column in MySQL/MariaDB

In MySQL/MariaDB the most efficient way to store uuid is in a BINARY(16) column. However, sometimes you want to obtain it as a formatted uuid string.

Given the following table structure, how would I obtain all uuids in a default formatted way?

CREATE TABLE foo (uuid BINARY(16)); 
like image 716
Lilleman Avatar asked May 11 '16 16:05

Lilleman


People also ask

Does MariaDB support UUID?

MariaDB starting with 10.7.The UUID data type was added in a MariaDB 10.7.

What is the datatype for UUID in MySQL?

In MySQL, a UUID value is a 128-bit number represented as a utf8 string, and the format in hexadecimal number will be as follows. Here, the first three numbers are generated from the low, middle, and high parts of a timestamp.

What is the datatype for UUID?

A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems.

Is UUID a binary?

The MySQL function UUID_TO_BIN() is used to convert the valid string UUID of human-readable format to the binary UUID in a compact format. In contrast, BIN_TO_UUID() converts the binary UUID to the string UUID. The data type of the result generated by the UUID_TO_BIN() function is VARBINARY(16).


2 Answers

The following would create the result I was after:

SELECT   LOWER(CONCAT(     SUBSTR(HEX(uuid), 1, 8), '-',     SUBSTR(HEX(uuid), 9, 4), '-',     SUBSTR(HEX(uuid), 13, 4), '-',     SUBSTR(HEX(uuid), 17, 4), '-',     SUBSTR(HEX(uuid), 21)   )) FROM foo; 
like image 118
Lilleman Avatar answered Sep 17 '22 14:09

Lilleman


MySQL 8 adds two new UUID functions:

  • UUID_TO_BIN
  • BIN_TO_UUID - this is the one you're looking for

So:

SELECT BIN_TO_UUID(uuid) FROM foo 
like image 29
Oleg Mikheev Avatar answered Sep 20 '22 14:09

Oleg Mikheev