Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing MySQL GUID/UUIDs

This is the best way I could come up with to convert a MySQL GUID/UUID generated by UUID() to a binary(16):

UNHEX(REPLACE(UUID(),'-','')) 

And then storing it in a BINARY(16)

Are there any implications of doing it this way that I should know of?

like image 906
thr Avatar asked Feb 13 '09 18:02

thr


People also ask

How does MySQL store UUID?

In MySQL, you can store UUID values in a compact format ( BINARY ) and display them in human-readable format ( VARCHAR ) with help of the following functions: UUID_TO_BIN. BIN_TO_UUID. IS_UUID.

Does MySQL supports UUID?

UUID() function in MySQL. This function in MySQL is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, “A Universally Unique Identifier (UUID) URN Namespace”. It is designed as a number that is universally unique.

What is the data type for GUID in MySQL?

GUID is a 16 byte binary SQL Server data type that is globally unique across tables, databases, and servers. The term GUID stands for Globally Unique Identifier and it is used interchangeably with UNIQUEIDENTIFIER. Execute the above line of SQL multiple times and you will see a different value every time.

Is UUID efficient?

The default representation for UUID, hash, and token values is often the hexadecimal notation. With a cardinality, the number of possible values, of only 16 per byte, it is far from efficient.


2 Answers

Not many implications. It will slow down the queries a little, but you will hardly notice it.

UNIQUEIDENTIFIER is stored as 16-byte binary internally anyway.

If you are going to load the binary into a client and parse it there, note the bit order, it may have other string representation than the initial NEWID().

Oracle's SYS_GUID() function is prone to this issue, converting it to a string gives different results on client and on server.

like image 67
Quassnoi Avatar answered Oct 09 '22 06:10

Quassnoi


From MySQL 8.0 and above you could use UUID_TO_BIN:

UUID_TO_BIN(string_uuid), UUID_TO_BIN(string_uuid, swap_flag)

Converts a string UUID to a binary UUID and returns the result. (The IS_UUID() function description lists the permitted string UUID formats.) The return binary UUID is a VARBINARY(16) value.

CREATE TABLE t (id binary(16) PRIMARY KEY);   INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true)); INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true)); INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true));  SELECT *, BIN_TO_UUID(id) FROM t; 

DB-Fiddle.com Demo

like image 23
Lukasz Szozda Avatar answered Oct 09 '22 06:10

Lukasz Szozda