Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL - TIME Data Type
Next article icon

PostgreSQL – UUID Data Type

Last Updated : 13 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The UUID (Universally Unique Identifier) is a 128-bit identifier defined by RFC 4122. It generates globally unique values using algorithms that ensure no duplication, making it ideal for distributed systems. PostgreSQL supports UUID as a data type and provides extensions for UUID generation, which is particularly useful in multi-database applications or distributed systems where unique identifiers are crucial.

In this article, we will explain the PostgreSQL UUID Data Type along with its syntax, examples, and usage scenarios. This guide will help us understand how to effectively implement and manage UUIDs in our PostgreSQL databases.

Why Use UUIDs in PostgreSQL?

UUIDs offer a key advantage over the SERIAL data type by ensuring uniqueness not only within a single database but across multiple databases or systems. This makes UUIDs an optimal choice for applications that require global uniqueness. UUIDs are commonly used in distributed systems and microservices architectures, where identifiers must be unique even across network boundaries.

Installing the UUID Extension in PostgreSQL

While PostgreSQL allows storing and comparing UUID values, it does not include built-in functions for generating them. Instead, it relies on third-party modules, such as the ‘uuid-ossp' module, which implements standard algorithms for UUID generation.

To install the uuid-ossp extension, execute the following command:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Generating UUIDs in PostgreSQL

The uuid-ossp module provides several functions to generate UUIDs based on different algorithms. These functions make it easy to create UUIDs directly within PostgreSQL, supporting various use cases and levels of randomness for unique key generation.

1. UUID Version 1

UUID version 1 combines the computer’s MAC address, the current timestamp, and a random value to produce a unique identifier. Use the ‘uuid_generate_v1()' function as shown below:

Query:

SELECT uuid_generate_v1();

Output

UUID Data Type in PostgreSQL

2. UUID Version 4

UUID version 4 generates a UUID based entirely on random numbers, ensuring a high degree of uniqueness. Use the ‘uuid_generate_v4()' function as follows:

Query:

SELECT uuid_generate_v4();

Output

Example of PostgreSQL UUID Data Type

Let us take a look at an example of UUID Data Type in PostgreSQL to better understand the concept. In this example we will make a table whose primary key is a UUID data type. In supplement, the values of the primary key column will be produced automatically through the ‘uuid_generate_v4()' function.

Query:

CREATE TABLE contacts (
contact_id uuid DEFAULT uuid_generate_v4 (),
first_name VARCHAR NOT NULL,
last_name VARCHAR NOT NULL,
email VARCHAR NOT NULL,
phone VARCHAR,
PRIMARY KEY (contact_id)
);

INSERT INTO contacts (first_name, last_name, email, phone)
VALUES
('Raju', 'Kumar', '[email protected]', '408-237-2345'),
('Nikhil', 'Aggarwal', '[email protected]', '408-237-2344'),
('Anshul', 'Aggarwal', '[email protected]', '408-237-2343'
);

SELECT * FROM contacts;

Output

UUID Data Type in PostgreSQL

Important Points About PostgreSQL UUID Data Type

  • UUID versions: PostgreSQL supports multiple versions of UUIDs (v1, v4, etc.), each using different algorithms for generation.
  • Extensions for UUIDs: PostgreSQL’s core does not natively generate UUIDs; it relies on extensions like ‘uuid-ossp' or ‘pgcrypto'.
  • UUID format: UUIDs are represented in a standard textual format (8-4-4-4-12 hexadecimal digits) which can be easily read and parsed by humans and systems.
  • Client-side vs. server-side generation: UUIDs can be generated on the client-side (in application code) or server-side (in the database). Client-side generation can reduce the load on the database.

Conclusion

PostgreSQL’s support for the UUID data type provides a reliable method for unique data identification across distributed systems and databases. By utilizing the uuid-ossp extension, PostgreSQL allows the generation of UUIDs with standard functions, enhancing the flexibility and security of our database designs. Using UUIDs also helps prevent conflicts across databases, making them ideal for scalable and distributed environments.



Next Article
PostgreSQL - TIME Data Type

R

RajuKumar19
Improve
Article Tags :
  • Databases
  • PostgreSQL
  • postgreSQL
  • postgreSQL-dataTypes

Similar Reads

  • PostgreSQL - Data Types
    PostgreSQL is a robust open-source relational database management system that supports a wide variety of data types. These data types are essential for defining the nature of the data stored in a database column, affecting storage, access, and manipulation. In this article, We will learn about the P
    5 min read
  • PostgreSQL - CHAR Data Type
    The CHAR data type in PostgreSQL is one of the essential character data types for storing fixed-length strings. Unlike VARCHAR, which stores variable-length data, CHAR is used when we need to store a fixed-length string. This article will explain the CHAR data type in PostgreSQL, its syntax, common
    5 min read
  • PostgreSQL - TEXT Data Type
    PostgreSQL provides a highly flexible character data type known as TEXT, designed to store character strings of virtually unlimited length. Unlike the VARCHAR data type, which can be limited to a specified length, the TEXT data type offers the same efficiency and performance without the length const
    3 min read
  • PostgreSQL - TIME Data Type
    In PostgreSQL, the TIME data type is essential for applications that require precise time tracking, such as scheduling systems and event logging. This data type allows for accurate time-based entries without storing date information. PostgreSQL’s TIME data type also supports fractional seconds for u
    4 min read
  • PostgreSQL - JSON Data Type
    JSON (JavaScript Object Notation) is a widely used format for storing data in the form of key-value pairs. Its popularity comes from being easy for humans to read and understand, making it ideal for communication between servers and clients. This readability and ease of use have made JSON a standard
    5 min read
  • PostgreSQL - Date Data Type
    PostgreSQL offers powerful DATE data type and date functions to efficiently handle date and time information. PostgreSQL DATE data type allows for storing and manipulating calendar dates while its robust set of date functions enables users to perform operations like date arithmetic and formatting. I
    4 min read
  • PostgreSQL - VARCHAR Data Type
    In the world of relational databases, PostgreSQL stands out with its robust support for various data types, including the flexible VARCHAR data type. This character data type allows us to store strings of variable length, making it an essential choice for many applications. In this article, we will
    3 min read
  • PostgreSQL - Array Data Type
    PostgreSQL provides an advanced and flexible feature known as the Array Data Type, which allows us to store multiple values in a single column. Arrays in PostgreSQL can be used with all built-in data types and even user-defined types, enabling a wide range of use cases. In this article, we will expl
    4 min read
  • PostgreSQL - INTEGER Data Type
    In PostgreSQL, the INTEGER data type is widely used for storing numerical data efficiently. It is a 4-byte data type that allows us to store whole numbers within a specified range, making it ideal for various use cases like population counts, active user statistics, and more. In this article, we wil
    4 min read
  • PostgreSQL - NUMERIC Data Type
    In PostgreSQL, the NUMERIC data type is designed for high-precision number storage by making it ideal for financial and scientific applications where accuracy is critical. It supports a large number of digits both before and after the decimal point, minimizing rounding errors. Understanding the nuan
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences