How to Generate UUID in PostgreSQL

preview_player
Показать описание
Disclaimer/Disclosure: Some of the content was synthetically produced using various Generative AI (artificial intelligence) tools; so, there may be inaccuracies or misleading information present in the video. Please consider this before relying on the content to make any decisions or take any actions etc. If you still have any concerns, please feel free to write them in a comment. Thank you.
---

Summary: Learn how to generate Universally Unique Identifiers (UUIDs) in PostgreSQL using built-in functions and extensions. UUIDs are unique identifiers often used in database tables for primary keys or other identification purposes.
---

Universally Unique Identifiers (UUIDs) are identifiers designed to be unique across both space and time. In PostgreSQL, generating UUIDs can be achieved using either built-in functions or extensions. Here's how you can generate UUIDs in PostgreSQL:

Using the uuid-ossp Extension

PostgreSQL provides the uuid-ossp extension, which includes functions for generating UUIDs. Before using these functions, ensure the extension is installed and enabled. You can install the extension using the following SQL command:

[[See Video to Reveal this Text or Code Snippet]]

Once the extension is installed, you can generate UUIDs using the uuid_generate_v4() function. This function generates a version 4 UUID, which is randomly generated. Here's how to use it:

[[See Video to Reveal this Text or Code Snippet]]

This query will return a UUID in the following format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx.

Using the gen_random_uuid() Function (PostgreSQL 13 and above)

Starting from PostgreSQL 13, a new function called gen_random_uuid() is introduced, which generates version 4 UUIDs without needing the uuid-ossp extension. This function is simpler to use and does not require enabling any extensions. Here's how to use it:

[[See Video to Reveal this Text or Code Snippet]]

This query will also return a UUID in the same format as uuid_generate_v4().

Generating UUIDs in Specific Columns

If you want to generate UUIDs for specific columns in a table, you can incorporate these functions into your INSERT statements. For example:

[[See Video to Reveal this Text or Code Snippet]]

In this example, the id column will be populated with a UUID generated by uuid_generate_v4().

Conclusion

Generating UUIDs in PostgreSQL is straightforward, whether you choose to use the uuid-ossp extension or the built-in gen_random_uuid() function introduced in PostgreSQL 13. UUIDs are commonly used as primary keys or unique identifiers in database tables, offering a reliable way to ensure uniqueness across distributed systems.
Рекомендации по теме
welcome to shbcf.ru