How to Generate a UUID in Any Programming Language
UUIDs prevent collisions in distributed systems. Here's how to generate them correctly across languages and what the different versions mean.
Every database row needs an ID. The question is whether that ID should come from the database (auto-increment) or be generated by your application (UUID). When you need IDs generated without database interaction, or across multiple systems, UUIDs are the answer.
Generate a UUID Now
In JavaScript
crypto.randomUUID() is built into modern browsers and Node.js 15+. No library needed. Returns a UUID v4 string. For older environments: import { v4 as uuidv4 } from 'uuid' and call uuidv4(). The uuid package is well-maintained and has 5M+ weekly downloads.
In Python
import uuid; str(uuid.uuid4()) — built into Python's standard library. For UUID v7 (time-ordered), the python-uuid7 package provides uuid7.uuid7(). No installation needed for v4.
In Other Languages
- Java: UUID.randomUUID().toString() — built-in
- Go: google/uuid package (uuid.New())
- Rust: uuid crate with rand feature
- PHP: Str::uuid() in Laravel, or ramsey/uuid package
- SQL (PostgreSQL): gen_random_uuid() — built-in
UUID v7 for Database Primary Keys
UUID v4 is random, which means adjacent insertions go to different parts of a B-tree index, causing fragmentation and slower queries over time. UUID v7 includes a millisecond timestamp prefix, so recently-created records have adjacent UUIDs. They sort chronologically. Database index performance is much closer to auto-increment integers. If you're using UUIDs as primary keys in PostgreSQL or MySQL, v7 is worth using.
Formatting note
UUIDs are case-insensitive: 550E8400-E29B-41D4-A716-446655440000 and 550e8400-e29b-41d4-a716-446655440000 are the same UUID. Store consistently (lowercase is conventional) and normalize on input if your system accepts user-supplied UUIDs.
Frequently Asked Questions
What is a UUID and what is it used for?+
What's the difference between UUID versions?+
Are UUIDs really unique?+
Should I use UUIDs or auto-increment integers for database IDs?+
🔧 Free Tools Used in This Guide
FreeToolKit Team
FreeToolKit Team
We build free browser-based tools and write practical guides that skip the fluff.
Tags: