Cover Image for MySQL UUID
141 views

MySQL UUID

A UUID (Universally Unique Identifier) is a 128-bit identifier that is globally unique and can be used as a primary key for database records. UUIDs are often used in distributed systems and databases to ensure that each record has a unique identifier, even when generated on different machines or at different times. MySQL provides support for storing UUIDs in binary or string format, and it has functions for generating and working with UUIDs.

In MySQL, you can use the UUID() function to generate a new UUID. For example:

SELECT UUID();

This will return a UUID in its hexadecimal string representation, like “550e8400-e29b-41d4-a716-446655440000.”

You can also store UUIDs in a table. To do so, create a column with a data type of BINARY(16) if you want to store the UUID in binary format, or CHAR(36) if you want to store it in string format (as a string of 36 characters).

For example, to create a table with a UUID column in binary format:

CREATE TABLE my_table (
    id BINARY(16) PRIMARY KEY,
    name VARCHAR(255)
);

To insert a new record with a UUID value:

INSERT INTO my_table (id, name) VALUES (UUID(), 'John Doe');

When working with UUIDs in MySQL, you may also need to use functions like UNHEX() and HEX() to convert between binary and string representations.

-- Insert a UUID in binary format
INSERT INTO my_table (id, name) VALUES (UNHEX('550e8400e29b41d4a716446655440000'), 'Jane Smith');

-- Select a UUID in string format
SELECT HEX(id) FROM my_table;

Remember that the choice between storing UUIDs in binary or string format depends on your specific requirements and the programming language and frameworks you are using to interact with the database. Some programming languages and frameworks may handle UUIDs more easily in one format or the other.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS