Welcome to our deep dive into the world of SQL UUIDs (Universally Unique Identifiers) and GUIDs (Globally Unique Identifiers)! 📝
In this tutorial, we'll explore:
UUIDs and GUIDs are special types of identifiers used to uniquely identify records within a database. They are typically used when primary keys based on auto-incrementing integers are not suitable, or when multiple databases need to communicate with each other.
Both UUIDs and GUIDs are 128-bit values, represented as a string of 32 hexadecimal digits (0-9 and A-F), separated by hyphens. For example:
550e8400-e29b-11d4-a716-446655440000
SQL does not have built-in support for generating UUIDs and GUIDs. However, most databases provide functions to generate them:
To generate a UUID in MySQL, use the UUID() function:
CREATE TABLE uuid_example (id UUID PRIMARY KEY);
INSERT INTO uuid_example (id) VALUES (UUID());To generate a UUID in PostgreSQL, use the gen_random_uuid() function:
CREATE TABLE uuid_example (id uuid PRIMARY KEY);
INSERT INTO uuid_example (id) VALUES (gen_random_uuid());In this section, we'll create a simple table with UUIDs and GUIDs, and then perform some common database operations.
CREATE TABLE uuid_example (
id UUID PRIMARY KEY,
name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO uuid_example (id, name) VALUES (UUID(), 'John Doe');
-- Query UUID records
SELECT * FROM uuid_example;CREATE TABLE uuid_example (
id uuid PRIMARY KEY,
name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO uuid_example (id, name) VALUES (gen_random_uuid(), 'John Doe');
-- Query UUID records
SELECT * FROM uuid_example;Which SQL function can be used to generate a UUID in MySQL?
With this, you've learned the basics of UUIDs and GUIDs in SQL! 🎉 Keep exploring and experimenting to master these powerful identifiers. Happy coding! 🤘