Optimizing UUID Storage in MySQL: Converting to a Number
While UUIDs offer uniqueness, their storage as strings in MySQL can hinder performance. To enhance data retrieval efficiency, it's advisable to store UUIDs as numbers instead.
Conversion Process
Insert Using UNHEX():
Insert the UUID into the BINARY field using the UNHEX() function, e.g.:
INSERT INTO Table (FieldBin) VALUES (UNHEX("110E8400E29B11D4A716446655440000"))
Query Using HEX():
To retrieve the UUID, use the HEX() function, e.g.:
SELECT HEX(FieldBin) AS FieldBin FROM Table
Example
require 'mysql2' client = Mysql2::Client.new( host: 'localhost', username: 'root', password: 'password', database: 'test_database' ) uuid_binary = client.query( 'SELECT HEX(FieldBin) AS FieldBin FROM test_table' ).first['FieldBin'] uuid = uuid_binary.insert(9, '-').insert(14, '-').insert(19, '-').insert(24, '-') puts uuid
By storing UUIDs as numbers, you can optimize data retrieval in MySQL, significantly improving query performance.
The above is the detailed content of How can I optimize UUID storage in MySQL and improve query performance?. For more information, please follow other related articles on the PHP Chinese website!