ToolsCourt
BlogUsing UUIDs as Database Primary Keys: Performance, Storage, and Best Practices
Dev9 min read·January 2025

Using UUIDs as Database Primary Keys: Performance, Storage, and Best Practices

When to use UUIDs over auto-increment, the index fragmentation problem, and how UUID v7 solves it.

Try the free tool
No signup. Runs in your browser. Takes 10 seconds.
Open UUID Generator

Why Use UUIDs Instead of Auto-Increment?

  • Distributed systems: Multiple databases can generate IDs independently without coordination
  • Merge-friendly: Combining data from multiple sources never causes ID collisions
  • Security: Auto-increment IDs reveal how many records you have and enable enumeration attacks
  • Offline-first apps: Mobile apps can generate IDs before syncing to server

The Index Fragmentation Problem

Database B-tree indexes store keys in sorted order. With auto-increment, each new ID is always larger than all existing ones — inserts go to the end of the index. Fast, sequential, cache-friendly.

With UUID v4 (random), each new ID is random — it inserts into a random position in the index. The database must: find the right position, potentially split an index page, update adjacent pages. At 10 million rows, this causes measurable performance degradation.

Primary Key TypeInsert Performance (10M rows)Storage Size
Integer (AUTO_INCREMENT)Baseline (100%)4–8 bytes
UUID v4 (VARCHAR 36)30–50% of baseline36 bytes
UUID v4 (BINARY 16)40–60% of baseline16 bytes
UUID v7 (BINARY 16)80–90% of baseline16 bytes

Best Practice: Store as BINARY(16)

-- MySQL: Store efficiently, display as string
CREATE TABLE users (
  id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID(), 1)),
  name VARCHAR(255)
);

INSERT INTO users (id, name) VALUES (UUID_TO_BIN(UUID(), 1), 'Rahul');
SELECT BIN_TO_UUID(id), name FROM users;

-- PostgreSQL: Native UUID type
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT
);

UUID v7 for New Applications

For new applications starting in 2024+, use UUID v7. It combines the distributed generation benefits of UUID with near-sequential insertion performance. PostgreSQL 17 (2024) has native UUID v7 support. Most ORMs (Prisma, TypeORM, Sequelize) have v7 packages available.

💡 Use the ToolsCourt UUID Generator to generate v7 UUIDs in your browser for testing — paste them into your database tooling or API requests to validate your schema.
Ready to try it?
Free, instant, no signup required.
Open UUID Generator Free →