How to Generate UUIDs (GUIDs) in JavaScript, Python & SQL
Learn how to generate Version 4 UUIDs in JavaScript, Python, and SQL. Includes code examples, storage tips, and our free Bulk UUID Generator for testing.
When building a database, you often need a unique identifier for each record. Simple integers (1, 2, 3...) work for small apps, but they fail in distributed systems where multiple servers create records simultaneously.
Enter the UUID (Universally Unique Identifier).
It’s a 128-bit number that is so unique, you could generate 1 billion of them every second for 85 years and probably never see a duplicate.
How to Generate UUIDs in Code
Here is how to generate a standard Version 4 (Random) UUID in popular languages.
JavaScript (Browser/Node)
Modern JS has a built-in crypto API:
const uuid = crypto.randomUUID();
console.log(uuid); // "36b8f84d-df4e-4d49-b662-bcde71a8764f"
Python
import uuid
print(uuid.uuid4())
SQL (PostgreSQL)
-- Requires "uuid-ossp" extension
SELECT uuid_generate_v4();
C# (.NET)
Guid myUuid = Guid.NewGuid();
Console.WriteLine(myUuid.ToString());
Anatomy of a UUID
A UUID is a 36-character string (32 hex digits + 4 hyphens).
Format: 8-4-4-4-12
Example: 123e4567-e89b-12d3-a456-426614174000
- Version: The first digit of the 3rd group indicates the version. For random UUIDs, it is always
4. - Variant: The first digit of the 4th group indicates the variant (usually
8,9,A, orB).
UUID Versions Explained
UUIDs come in different versions, each generated using a different method.
Version 1 (Timestamp + MAC Address)
Generated from the current timestamp and the machine’s MAC address. This provides uniqueness but reveals the machine’s identity and the time of creation, which can be a privacy concern.
Use Case: Ordered database keys where you want chronological sorting.
Version 4 (Random)
The most common version. Generated using random or pseudo-random numbers. Has 122 bits of randomness, making collisions astronomically unlikely.
Use Case: General-purpose unique identifiers where ordering doesn’t matter.
Version 5 (Name-based SHA-1)
Generated by hashing a namespace and a name with SHA-1. Deterministic: the same inputs always produce the same UUID.
Use Case: Creating consistent IDs from URLs or other identifiable data.
Most developers use Version 4 because it’s simple, secure, and has no privacy concerns.
When to Use UUIDs vs. Auto-Increment IDs
| Scenario | Use UUID | Use Auto-Increment |
|---|---|---|
| Single database server | Optional | Yes |
| Distributed system (multiple databases) | Yes | No |
| Offline-first apps (sync later) | Yes | No |
| Public-facing URLs | Yes (harder to scrape) | No |
| Need ordered data | No | Yes |
| Database performance priority | No | Yes |
Why UUIDs for distributed systems?
If you have two servers creating records at the same time, auto-increment IDs will collide. UUIDs don’t require coordination between servers.
Example: A mobile app that creates records offline. When it syncs, those records need IDs that won’t conflict with records created on other devices.
Common Mistakes to Avoid
Storing UUIDs as Strings
Many developers store UUIDs as 36-character VARCHAR fields. This wastes space.
Bad:
CREATE TABLE users (
id VARCHAR(36) PRIMARY KEY -- 36 bytes
);
Good (PostgreSQL):
CREATE TABLE users (
id UUID PRIMARY KEY -- 16 bytes
);
Good (MySQL):
CREATE TABLE users (
id BINARY(16) PRIMARY KEY -- 16 bytes
);
By storing as binary, you save 20 bytes per row. On a table with 10 million rows, that’s 200 MB saved.
Using UUIDs for Every Table
UUIDs are slower than integers for indexing. If you don’t need distributed uniqueness, stick with auto-increment IDs.
Benchmark: Integer primary keys are 2-3x faster for lookups because they’re smaller and sequential.
Not Removing Hyphens for Storage
When storing in a BINARY field, strip the hyphens first. Otherwise, you’re storing unnecessary characters.
const uuidWithoutHyphens = uuid.replace(/-/g, '');
const buffer = Buffer.from(uuidWithoutHyphens, 'hex');
Confusing UUIDs with Security Tokens
UUIDs aren’t cryptographically secure random tokens. Don’t use them for:
- Password reset tokens
- Session IDs
- API keys
For security tokens, use crypto.randomBytes(32) or a library like nanoid.
Pro Tips
Prefixing UUIDs for Readability
Some systems prefix UUIDs with a type identifier for debugging purposes.
Example (Stripe-style):
user_550e8400-e29b-41d4-a716-446655440000
order_6ba7b810-9dad-11d1-80b4-00c04fd430c8
This makes logs easier to read and prevents mixing up different entity types.
Converting Between Formats
You may need to convert between different representations.
// Standard: "550e8400-e29b-41d4-a716-446655440000"
// No hyphens: "550e8400e29b41d4a716446655440000"
// Uppercase: "550E8400-E29B-41D4-A716-446655440000"
// Braced (Microsoft): "{550e8400-e29b-41d4-a716-446655440000}"
// URN: "urn:uuid:550e8400-e29b-41d4-a716-446655440000"
Generating Sequential UUIDs (ULID)
If you want the uniqueness of UUIDs but with timestamp ordering, use ULID (Universally Unique Lexicographically Sortable Identifier).
// ULID example: 01ARZ3NDEKTSV4RRFFQ69G5FAV
// First 10 chars = timestamp, last 16 = random
This gives you both sortability and uniqueness without coordination.
Database-Generated vs. Application-Generated
Where should you generate the UUID?
Database-generated:
INSERT INTO users (id, name) VALUES (uuid_generate_v4(), 'Alice');
Pros: Consistent generation, no application dependency.
Cons: Can’t reference the ID before insertion (unless you use RETURNING).
Application-generated:
const id = crypto.randomUUID();
await db.query('INSERT INTO users (id, name) VALUES ($1, $2)', [id, 'Alice']);
Pros: You know the ID before insertion (useful for nested inserts).
Cons: Depends on application-level UUID library availability.
Recommendation: Generate in the app if you need the ID upfront (e.g., for related records). Otherwise, let the database handle it.
Real-World Use Cases
Database Primary Keys
UUIDs shine in multi-tenant systems where different databases need to merge data.
Example: A SaaS app with separate databases per customer. When a customer exports/imports data, UUIDs prevent ID conflicts.
File Naming
Generating unique filenames for user uploads.
const filename = `${crypto.randomUUID()}.jpg`;
// Result: "3f4a8d2c-9e1b-4d5f-a123-9876543210ab.jpg"
Distributed Tracing
Each request in a microservices architecture gets a UUID for tracking across services.
const requestId = crypto.randomUUID();
logger.info(`[${requestId}] Processing order`);
Cache Keys
Using UUIDs as cache keys ensures no collisions.
const cacheKey = `session_${crypto.randomUUID()}`;
Frequently Asked Questions
Can two UUIDs ever be the same?
The probability is so low it’s effectively zero. With 122 bits of randomness (Version 4), you’d need to generate 2.71 quintillion UUIDs to have a 50% chance of a single collision.
Are UUIDs case-sensitive?
No. 550e8400-e29b-41d4-a716-446655440000 and 550E8400-E29B-41D4-A716-446655440000 are the same UUID. Lowercase is conventional.
How do I generate a UUID in SQL?
It depends on the database. PostgreSQL uses SELECT uuid_generate_v4(); (requires the uuid-ossp extension). MySQL 8.0+ uses SELECT UUID();. SQL Server uses SELECT NEWID();.
Can I use UUIDs in URLs?
Yes. UUIDs are URL-safe (no special characters except hyphens). They’re often used in public-facing URLs because they’re harder to guess than sequential integers.
What is the difference between UUID and GUID?
None. GUID (Globally Unique Identifier) is Microsoft’s name for UUID. They’re the same thing.
Use the Online Generator
Need a quick batch of UUIDs for testing or a config file?
Use our Free UUID Generator. It can create up to 1,000 unique IDs instantly, with options to remove hyphens, uppercase characters, or wrap them in braces. Perfect for seeding databases, generating test data, or creating unique filenames.
Related Calculators
Related Articles
- Color Theory Basics for Web Design
Master color theory for web design including the color wheel, complementary palettes, WCAG contrast requirements, and color psychology to create effective interfaces.
- How to Minify CSS for Faster Websites
Learn what CSS minification does, why it speeds up your website, what it removes from your stylesheets, and best practices for minifying CSS in production.
- Cron Job Examples for Common Tasks (Copy-Paste Ready)
Practical cron job examples with clear explanations. Copy-paste ready crontab schedules for backups, reports, cleanup, monitoring, and automation tasks.
- Common JSON Syntax Errors and How to Fix Them
Fix JSON syntax errors fast with this developer guide. Learn the top 5 JSON parsing errors, before/after examples, and debugging techniques to validate JSON instantly.
Share this article
Have suggestions for this article?