See " Generating v4 UUIDs in MySQL" for a way to generate potentially more desirable UUIDs. When working with MySQL it is common to choose auto incrementing integer primary keys however, there are situations where using a GUID/UUID is desirable. If everything went well, at the end you should have output similar to: +-+-+ VALUES (uuid_to_bin(uuid()), 'Larry Page') Here's an example where a table users uses binary UUIDs for its primary key: CREATE TABLE users MySQL v8.0.0 (2016) added the function UUID_TO_BIN() which does the same thing: SELECT uuid_to_bin("f7c26694-aac6-4333-91c9-72c4441430e2") AS uuid_bin +-+Īnd it's easy to perform the reverse here: SELECT lower( insert( insert( insert( insert( Even better, comparison and sorting will use the numeric value of the column, which will perform much better than a string.Īll versions of MySQL can use UNHEX() and REPLACE() to do this: SELECT UNHEX(REPLACE("f7c26694-aac6-4333-91c9-72c4441430e2", "-", "")) AS unhex_replace +-+ The BINARY type isn't affected by the table character set (such as utf8mb4), it uses the binary character set and collation. See the UUID function page for more details on UUIDs. If we strip the hyphens and convert the remaining 32 characters to BINARY, we can store UUIDs in only 16 bytes. The UUID data type is intended for the storage of 128-bit UUID (Universally Unique Identifier) data. A key point to note about UUIDs is that they are designed such that they are globally unique in space and time. UUIDs are supposed to be only 16 bytes, can't we do better? Binary UUID columns The MySQL UUID() function is used to return a Universal Unique Identifier (UUID) generated according to RFC 4122, A Universally Unique IDentifier (UUID) URN Namespace. Universally unique identifiers (UUIDs) are 128-bit (16-byte) numbers that are designed to be globally unique, and as a result they make for great primary keys. A UUID is just a 128-bit value and it is usually represented in human-readable format as an UTF8 string composed of 5 groups of hexadecimal characters separated by dashes. Why You Should Use UUIDs for Your Primary Keys
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |