mysql
  1. mysql-uuid

UUID - (MySQL Misc)

In MySQL, a UUID (Universally Unique Identifier) is a 128-bit string of characters that is used to uniquely identify rows in a table. UUIDs are useful for generating primary keys for tables because they can be generated on any system and are guaranteed to be unique.

Syntax

To create a column with a UUID in MySQL, you can use the following syntax:

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

The BINARY(16) column will store the UUID values. You can also use the UUID() function to generate UUID values:

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

Example

Let's say we want to create a table called "users" that has a UUID column for the user ID. Here's how we can do it:

CREATE TABLE users (
    id BINARY(16) PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(50)
);

We can then insert a new user into the table and generate a UUID using the UUID() function:

INSERT INTO users (id, name, email) VALUES (UUID(), 'John', 'john@example.com');

Explanation

In the example above, we created a table called "users" with a UUID column for the user ID. We then inserted a new user into the table and generated a UUID using the UUID() function. The UUID value is a 128-bit string of characters that uniquely identifies the user in the table.

Use

UUIDs are useful for generating unique identifiers for rows in a table. They can be generated on any system and are guaranteed to be unique, making them ideal for distributed systems. They are also useful for situations where you need to generate IDs before inserting records into the database.

Important Points

  • UUID values are stored as 128-bit strings of characters in a binary column.
  • You can use the UUID() function to generate UUID values.
  • UUIDs are guaranteed to be unique, making them useful for generating primary keys for tables.
  • UUIDs are useful for distributed systems and situations where you need to generate IDs before inserting records.

Summary

In this tutorial, we discussed how to use UUIDs in MySQL to generate unique identifiers for rows in a table. We covered the syntax, example, explanation, use, and important points of using UUIDs in MySQL. With this knowledge, you can now use UUIDs to generate unique primary keys for your tables in MySQL.

Published on: