▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/uuids/code-examples$ _

UUID Code Examples

Random v4, time-ordered v7 and name-based v3/v5 UUIDs in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

The examples below generate random version 4 UUIDs in every language, and, where the library supports them, time-ordered v7 and name-based v5 (or v3) UUIDs, then parse a UUID string and read its version. The guide explains the 128-bit layout, which version fits which job and where UUIDs go wrong in databases and APIs. Prefer no code? The interactive UUID generator does the same in the browser.

Anatomy of a UUID

A UUID is a 128-bit value written as 32 hex digits in five groups, 8-4-4-4-12, for example 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f. Two fields are fixed by the format: the first digit of the third group is the version (the 4 in 4c3e), and the first digit of the fourth group holds the variant, which is 8, 9, a or b for standard UUIDs. RFC 9562 (May 2024) defines the format and replaces RFC 4122, adding versions 6, 7 and 8 and the all-ones Max UUID next to the all-zeros Nil UUID.

Choosing a version

  • v4 (random): 122 random bits after the 6 fixed ones. A duplicate becomes a 50% likelihood only after about 2.7 × 1018 UUIDs, so coordination between machines is unnecessary, provided the bits come from a proper source.
  • v7 (time-ordered): a 48-bit Unix timestamp in milliseconds, then the version, then 74 random bits. UUIDs created later sort later, which keeps B-tree indexes compact; RFC 9562 recommends v7 over v1 and v6 for new systems.
  • v5 and v3 (name-based): a SHA-1 (v5) or MD5 (v3) hash of a namespace UUID followed by a name. The same pair always gives the same UUID: example.com in the DNS namespace is cfbff0d1-9375-5685-968c-48ce8b15ae17 in v5 and 9073926b-929f-31c2-abc9-fad77ae3e8eb in v3, in every language. Prefer v5 unless an existing system already uses v3.
  • v1 (time and node): a 60-bit timestamp with 100-nanosecond resolution plus a node ID that is traditionally the MAC address, which reveals the machine and the creation time.

Randomness and security

The built-in v4 functions on this page (crypto.randomUUID(), uuid.uuid4(), UUID.randomUUID(), Guid.NewGuid(), SecureRandom.uuid, uuid.New(), ramsey/uuid, Boost) all read the operating system's cryptographic generator, so their output is not predictable. Hand-written v4 code built on Math.random() or mt_rand() is a different story: colliding or guessable IDs follow. Even with a good source, RFC 9562 advises against treating a UUID as a secret or an access token; a v7 UUID also discloses when it was created. Use UUIDs to identify things, and a separate 128-bit or longer random token to authorize.

Common mistakes

  • Storing the text form. As CHAR(36) a UUID takes 36 bytes plus overhead; BINARY(16) in MySQL or the native uuid type in PostgreSQL takes 16.
  • Random v4 as a clustered primary key. Each insert lands on a random index page, which splits pages and inflates the index on large tables. Use v7, or keep a sequential key and add the UUID as a secondary column.
  • Mixed byte orders. .NET's Guid.ToByteArray() writes the first three groups little-endian, so bytes copied to Java, Go or PostgreSQL can turn into a different UUID. SQL Server also sorts uniqueidentifier values by their last group first.
  • Strict string comparisons. RFC 9562 output is lowercase but parsers must accept uppercase. Normalize to lowercase before comparing or using a UUID as a map key, and validate with a parser rather than a regular expression that hard-codes version 4.
  • Hashing only the name. A name-based UUID hashes the namespace bytes and the name together; skipping the namespace gives a valid-looking UUID that no other implementation reproduces.

Common Use Cases

  • Primary keys for database tables, preferably v7 for index locality
  • IDs created on several servers or offline clients without a central counter
  • Request, correlation and trace IDs in logs and microservices
  • Message, job and event IDs for queues and event sourcing
  • Stable, repeatable IDs derived from names or URLs with v5
  • Unique names for uploaded files and storage objects

UUID Code Examples in PHP

Generate UUIDs in PHP using the popular ramsey/uuid library. Supports UUID v1, v4, v5, and v7 with excellent performance and RFC 4122 compliance.

<?php
require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;

// Generate UUID v4 (random)
$uuid4 = Uuid::uuid4();
echo $uuid4->toString();  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

// Generate UUID v7 (timestamp-ordered, recommended for databases)
$uuid7 = Uuid::uuid7();
echo $uuid7->toString();  // Example: 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b

// Generate UUID v5 (namespaced)
$namespace = Uuid::NAMESPACE_DNS;
$name = 'example.com';
$uuid5 = Uuid::uuid5($namespace, $name);
echo $uuid5->toString();  // Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

// Parse and validate UUID
$uuidString = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f';
if (Uuid::isValid($uuidString)) {
    $uuid = Uuid::fromString($uuidString);
    echo $uuid->getVersion();  // Outputs: 4
}

How it works in PHP

Install via Composer: composer require ramsey/uuid. UUID v4 uses random bytes for maximum uniqueness. UUID v7 is timestamp-ordered, ideal for database primary keys (better indexing than v4). UUID v5 is deterministic based on namespace + name.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b
cfbff0d1-9375-5685-968c-48ce8b15ae17
4

PHP notes

  • PHP has no built-in UUID function; ramsey/uuid or symfony/uid provide v1 to v8.
  • Store with $uuid->getBytes() in a BINARY(16) column and read back with Uuid::fromBytes().
  • Laravel's Str::uuid() returns a v4 and Str::orderedUuid() a time-ordered UUID, both via ramsey/uuid.

UUID Code Examples in JavaScript

Generate UUIDs in JavaScript using the native crypto.randomUUID() API (modern browsers/Node.js 15.6+) or the popular uuid npm package for broader support.

// Modern browsers and Node.js 15.6+ (native API)
const uuid = crypto.randomUUID();
console.log(uuid);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

// Using uuid npm package (install: npm install uuid)
import { v4 as uuidv4, v5 as uuidv5, v7 as uuidv7 } from 'uuid';

// UUID v4 (random)
const uuid4 = uuidv4();
console.log(uuid4);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

// UUID v7 (timestamp-ordered)
const uuid7 = uuidv7();
console.log(uuid7);  // Example: 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b

// UUID v5 (namespaced)
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // DNS namespace
const name = 'example.com';
const uuid5 = uuidv5(name, NAMESPACE);
console.log(uuid5);  // Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

// Validate UUID
import { validate, version } from 'uuid';
if (validate(uuid4)) {
    console.log('Version:', version(uuid4));  // Outputs: 4
}

How it works in JavaScript

Native crypto.randomUUID() generates UUID v4 with zero dependencies. The uuid npm package provides more options including v7 (timestamp-ordered, best for databases). Use v7 for sortable IDs.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b
cfbff0d1-9375-5685-968c-48ce8b15ae17
4

JavaScript notes

  • crypto.randomUUID() only exists in secure contexts (HTTPS or localhost) in browsers; on plain HTTP it is undefined.
  • In Node.js it is available as require('node:crypto').randomUUID() since 14.17, and as a global since 19.
  • The uuid package added v7() in version 10; note its argument order v5(name, namespace).

UUID Code Examples in Python

Generate UUIDs in Python using the built-in uuid module. No external dependencies required. Supports UUID1, UUID4, and UUID5.

import uuid

# UUID v4 (random)
uuid4 = uuid.uuid4()
print(uuid4)  # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
print(str(uuid4))  # String representation

# UUID v1 (timestamp + MAC address)
uuid1 = uuid.uuid1()
print(uuid1)  # Example: 6ba7b810-9dad-11d1-80b4-00c04fd430c8

# UUID v5 (namespaced)
namespace = uuid.NAMESPACE_DNS
name = 'example.com'
uuid5 = uuid.uuid5(namespace, name)
print(uuid5)  # Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

# Parse and validate UUID
uuid_string = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f'
parsed_uuid = uuid.UUID(uuid_string)
print(parsed_uuid.version)  # Outputs: 4
print(parsed_uuid.hex)  # Hex without dashes: 3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f

# Generate multiple UUIDs
uuids = [str(uuid.uuid4()) for _ in range(5)]
print(uuids)

How it works in Python

The uuid module is part of Python's standard library. UUID4 uses os.urandom() for cryptographic randomness. UUID1 includes timestamp and MAC address (less private). UUID5 is deterministic for given namespace+name.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
6ba7b810-9dad-11d1-80b4-00c04fd430c8
cfbff0d1-9375-5685-968c-48ce8b15ae17
4
3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f

Python notes

  • Python 3.14+ adds uuid.uuid7(), uuid6() and uuid8(), plus uuid.NIL and uuid.MAX; earlier versions need a package for v7.
  • uuid.UUID(s) raises ValueError on invalid input; check .version as well if only one version is allowed.
  • Django's UUIDField maps to the native uuid type on PostgreSQL and to char(32) on most other databases.

UUID Code Examples in Java

Generate UUIDs in Java using the built-in java.util.UUID class. Provides UUID v4 (random) and v3 (namespaced) generation with no external dependencies.

import java.util.UUID;
import java.nio.charset.StandardCharsets;
import java.nio.ByteBuffer;

public class UuidExample {
    public static void main(String[] args) {
        // UUID v4 (random)
        UUID uuid4 = UUID.randomUUID();
        System.out.println(uuid4);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

        // UUID v3 (namespaced with MD5)
        UUID uuid3 = generateUuidV3("example.com");
        System.out.println(uuid3);  // Always same: 9073926b-929f-31c2-abc9-fad77ae3e8eb

        // Parse UUID from string
        String uuidString = "3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f";
        UUID parsed = UUID.fromString(uuidString);
        System.out.println(parsed.version());  // Outputs: 4

        // Generate multiple UUIDs
        for (int i = 0; i < 5; i++) {
            System.out.println(UUID.randomUUID());
        }
    }

    // Helper method for UUID v3 generation
    private static UUID generateUuidV3(String name) {
        // A v3 UUID is the MD5 of the namespace UUID's 16 bytes followed by the name
        UUID namespaceDns = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
        byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
        ByteBuffer buffer = ByteBuffer.allocate(16 + nameBytes.length);
        buffer.putLong(namespaceDns.getMostSignificantBits());
        buffer.putLong(namespaceDns.getLeastSignificantBits());
        buffer.put(nameBytes);
        // nameUUIDFromBytes applies MD5 and sets the version (3) and variant bits itself
        return UUID.nameUUIDFromBytes(buffer.array());
    }
}

How it works in Java

UUID.randomUUID() draws its 122 random bits from SecureRandom. For name-based UUIDs Java only ships v3: UUID.nameUUIDFromBytes() MD5-hashes the bytes it receives and sets the version and variant itself, so the helper passes the 16 bytes of the DNS namespace UUID followed by the name, which reproduces the standard v3 value for example.com.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
9073926b-929f-31c2-abc9-fad77ae3e8eb
4

Java notes

  • The JDK has no v5 or v7 generator; libraries such as java-uuid-generator (com.fasterxml.uuid) provide them.
  • UUID.compareTo() compares the two halves as signed longs, so its order differs from the string order for UUIDs starting with 8 to f.
  • Hibernate 6.2+ can generate UUID keys with @UuidGenerator, including a time-based style.

UUID Code Examples in C#

Generate UUIDs (called GUIDs in .NET) using the System.Guid struct. Built into .NET Framework, .NET Core, and .NET 5+.

using System;
using System.Collections.Generic;

class UuidExample
{
    static void Main()
    {
        // Generate new GUID (UUID v4)
        Guid guid = Guid.NewGuid();
        Console.WriteLine(guid);  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

        // Format variations
        Console.WriteLine(guid.ToString());           // Default: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
        Console.WriteLine(guid.ToString("N"));        // No dashes: 3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f
        Console.WriteLine(guid.ToString("D"));        // With dashes (default)
        Console.WriteLine(guid.ToString("B"));        // Braces: {3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f}
        Console.WriteLine(guid.ToString("P"));        // Parentheses: (3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f)

        // Parse GUID from string
        string guidString = "3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f";
        if (Guid.TryParse(guidString, out Guid parsed))
        {
            Console.WriteLine($"Parsed: {parsed}");
        }

        // Generate multiple GUIDs
        var guids = new List<Guid>();
        for (int i = 0; i < 5; i++)
        {
            guids.Add(Guid.NewGuid());
        }

        // Empty GUID
        Guid empty = Guid.Empty;  // 00000000-0000-0000-0000-000000000000
        Console.WriteLine($"Empty: {empty}");
    }
}

How it works in C#

Guid.NewGuid() generates UUID v4 using cryptographically secure random number generation. The Guid struct provides multiple formatting options. In C#, UUIDs are called GUIDs (Globally Unique Identifiers).

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
3d6f9e647d8a4c3e8f2b1a4e5c6d7e8f
{3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f}
(3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f)
00000000-0000-0000-0000-000000000000

C# notes

  • .NET 9+ adds Guid.CreateVersion7() for time-ordered GUIDs; Guid.NewGuid() stays v4.
  • ToString("N"), "D", "B" and "P" select the formats; output is lowercase.
  • Use new Guid(bytes, bigEndian: true) and TryWriteBytes(span, bigEndian: true, out _) (.NET 8+) when bytes travel to other platforms.

UUID Code Examples in C++

Generate UUIDs in C++ using Boost.UUID (most popular) or a custom implementation with <random>. Boost provides RFC 4122 compliant UUID generation.

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>
#include <string>

int main() {
    // UUID v4 (random) using Boost
    boost::uuids::random_generator gen;
    boost::uuids::uuid uuid = gen();

    std::cout << uuid << std::endl;  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

    // Convert to string
    std::string uuid_str = boost::uuids::to_string(uuid);
    std::cout << uuid_str << std::endl;

    // Generate multiple UUIDs
    for (int i = 0; i < 5; ++i) {
        std::cout << gen() << std::endl;
    }

    // UUID v5 (namespaced)
    boost::uuids::name_generator_sha1 name_gen(boost::uuids::ns::dns());
    boost::uuids::uuid uuid5 = name_gen("example.com");
    std::cout << uuid5 << std::endl;  // Always same

    // Parse UUID from string
    std::string uuid_string = "3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f";
    boost::uuids::string_generator string_gen;
    boost::uuids::uuid parsed = string_gen(uuid_string);
    std::cout << parsed << std::endl;

    return 0;
}

// Compile: g++ -std=c++11 uuid_example.cpp

How it works in C++

Install Boost with a package manager or from boost.org. Boost.UUID is header-only. random_generator creates v4 UUIDs from a ChaCha20/12 generator seeded by std::random_device (Boost 1.86+; older releases read the operating system's entropy source directly), name_generator_sha1 creates deterministic v5 UUIDs, and string_generator parses the text form.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
cfbff0d1-9375-5685-968c-48ce8b15ae17

C++ notes

  • Create one random_generator and reuse it, but not across threads without a lock: Boost documents its classes as only as thread-safe as an int.
  • Boost 1.86+ adds time_generator_v7 for v7 UUIDs; random_generator_mt19937 is discouraged since that release.
  • boost::uuids::uuid is a plain 16-byte value; version() and is_nil() inspect it without parsing the string.

UUID Code Examples in Ruby

Generate UUIDs in Ruby using the built-in SecureRandom.uuid method. No gems required for basic UUID v4 generation.

require 'securerandom'

# UUID v4 (random)
uuid = SecureRandom.uuid
puts uuid  # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

# Generate multiple UUIDs
5.times do
  puts SecureRandom.uuid
end

# Using UUIDTools gem for more features (gem install uuidtools)
require 'uuidtools'

# UUID v4
uuid4 = UUIDTools::UUID.random_create
puts uuid4.to_s  # Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

# UUID v5 (namespaced)
namespace = UUIDTools::UUID_DNS_NAMESPACE
name = 'example.com'
uuid5 = UUIDTools::UUID.sha1_create(namespace, name)
puts uuid5.to_s  # Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

# Parse UUID from string
uuid_string = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f'
parsed = UUIDTools::UUID.parse(uuid_string)
puts parsed.valid?  # Outputs: true

# In Rails models (ActiveRecord)
# class User < ApplicationRecord
#   before_create :generate_uuid
#
#   private
#   def generate_uuid
#     self.id = SecureRandom.uuid
#   end
# end

How it works in Ruby

SecureRandom.uuid is built into Ruby (no gems needed). For advanced features like UUID v5 and validation, use the uuidtools gem. In Rails, you can use UUID columns in PostgreSQL with native support.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
cfbff0d1-9375-5685-968c-48ce8b15ae17
true

Ruby notes

  • Ruby 3.3+ adds SecureRandom.uuid_v7 and uuid_v4 (an alias of uuid).
  • Rails migrations take id: :uuid on PostgreSQL, using the database's gen_random_uuid() by default.
  • Without a gem, a format check is /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/i.

UUID Code Examples in Go

Generate UUIDs in Go using the google/uuid package. Most popular UUID library for Go with support for UUID v1, v4, v5, and v7.

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    // UUID v4 (random)
    uuid4 := uuid.New()
    fmt.Println(uuid4.String())  // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f

    // UUID v7 (timestamp-ordered, best for databases)
    uuid7, err := uuid.NewV7()
    if err != nil {
        panic(err)
    }
    fmt.Println(uuid7.String())  // Example: 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b

    // UUID v5 (namespaced)
    namespace := uuid.NameSpaceDNS
    name := "example.com"
    uuid5 := uuid.NewSHA1(namespace, []byte(name))
    fmt.Println(uuid5.String())  // Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17

    // Parse UUID from string
    uuidString := "3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f"
    parsed, err := uuid.Parse(uuidString)
    if err != nil {
        fmt.Println("Invalid UUID")
    }
    fmt.Println("Version:", parsed.Version())  // Outputs: 4

    // Generate multiple UUIDs
    for i := 0; i < 5; i++ {
        fmt.Println(uuid.New())
    }

    // Nil UUID
    nilUUID := uuid.Nil
    fmt.Println(nilUUID)  // 00000000-0000-0000-0000-000000000000
}

// Install: go get github.com/google/uuid

How it works in Go

Install with go get github.com/google/uuid. uuid.New() generates UUID v4. uuid.NewV7() generates timestamp-ordered UUIDs ideal for database primary keys. The package is maintained by Google.

Sample output

3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b
cfbff0d1-9375-5685-968c-48ce8b15ae17
4
00000000-0000-0000-0000-000000000000

Go notes

  • uuid.New() panics if the random source fails; uuid.NewRandom() returns an error instead.
  • uuid.NewV7() requires github.com/google/uuid v1.6.0 or later.
  • uuid.UUID is a [16]byte, so it works as a map key and compares with ==.

Try the Interactive Generator

Need values right now rather than code? The UUID generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE UUID GENERATOR →