UUID vs Auto-Increment IDs: Which Primary Key Should You Use?
Size, index performance, security and UUID v7 compared, with real examples for PostgreSQL, MySQL and MongoDB, and the hybrid most apps need.

For a single database behind one application, an auto-increment integer is still the simplest and fastest primary key. Choose a UUID when IDs must be created outside the database (in the browser, on several servers, or offline), when records from different databases get merged, or when IDs appear in URLs and must not reveal how many records you have. And if you choose UUIDs, prefer UUID v7 over the usual random v4 for primary keys, because v7 values are ordered by time and keep your indexes efficient.
Here is the reasoning behind each choice, with real numbers, code for MySQL, PostgreSQL and MongoDB, and the hybrid approach I use in most projects.
The short comparison
Auto-increment (BIGINT) |
UUID v4 (random) | UUID v7 (time-ordered) | |
|---|---|---|---|
| Size | 8 bytes | 16 bytes (36 characters as text) | 16 bytes (36 characters as text) |
| Generated by | The database, on insert | Anyone, anywhere | Anyone, anywhere |
| Insert order in the index | Always at the end | Random positions | Roughly at the end |
| Reveals record count or growth | Yes | No | No (but reveals creation time) |
| Guessable | Yes (/orders/1001 → /orders/1002) |
No | Practically no |
| Easy to read and type | Yes | No | No |
| Safe to merge across databases | No (collisions) | Yes | Yes |
When auto-increment is the better choice
- One database, IDs never leave your system. Internal tables (join tables, logs, settings, line items) gain nothing from UUIDs.
- Write-heavy tables. New rows always go to the end of the index, which is the cheapest possible insert for a B-tree.
- Humans read the IDs. Support staff can say "order 48213" on the phone. Nobody reads a UUID out loud.
The two real costs are that sequential IDs leak information (sign up twice, a week apart, and the difference tells you how many customers a competitor gained), and they make enumeration easy: if /invoices/1001 exists, so does /invoices/1000. Proper authorization checks stop enumeration from becoming a data leak, but many breaches start exactly there.
When a UUID is the better choice
- The client creates the ID. A mobile app that works offline, or a frontend doing optimistic updates, can create the record's final ID before the server ever sees it.
- Several databases or services. Sharded databases, multi-region writes, or merging data from separate installations all work without a central counter.
- Public IDs in URLs and APIs.
/invoices/0193f4c8-…reveals nothing and cannot be guessed. - Idempotency. A UUID generated by the client and sent with a payment request lets the server recognize a retried request and process it once.
Why v4 UUIDs hurt as primary keys, and v7 does not
A v4 UUID is 122 random bits. That is perfect for uniqueness, but because every new key lands at a random position in the primary key index, the database keeps touching and splitting pages all over the index instead of appending at the end. On a small table you will never notice. On a table with tens of millions of rows that is written constantly, it shows up as index bloat, more disk I/O and slower inserts. It is worst in MySQL's InnoDB, where the table itself is stored in primary key order.
UUID v7 (standardized in RFC 9562 in 2024) fixes this by starting with a 48-bit Unix timestamp in milliseconds, followed by random bits. New values sort after older ones, so inserts behave almost like an auto-increment, while you keep every benefit of a UUID:
01a1c6a6-cbc1-738f-afb1-0b1b44148899
└───────────┘ │
creation time │
(milliseconds)└ version 7
The trade-off is that a v7 ID reveals roughly when the record was created. For most applications that is harmless; for some (anonymous reports, for example) it is not, and v4 is the better choice there.
Generating UUIDs in code
// Node.js 15.6+ and browsers: random v4, built in
crypto.randomUUID(); // e.g. 'd55cb1fc-f4c3-45c1-9deb-69a6d204772d'
// Time-ordered v7, with the uuid package (version 10 or later)
import { v7 as uuidv7 } from 'uuid';
uuidv7(); // e.g. '01a1c6a6-cbc1-738f-afb1-0b1b44148899'
For test data, fixtures or a quick idempotency key, the UUID Generator creates up to 50 v4 UUIDs at once.
In PostgreSQL
PostgreSQL has a native 16-byte uuid type, so there is no reason to store UUIDs as text:
-- PostgreSQL 13+: random v4 built in
CREATE TABLE invoices (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
total_cents bigint NOT NULL
);
-- PostgreSQL 18+: time-ordered v7 built in
CREATE TABLE events (
id uuid PRIMARY KEY DEFAULT uuidv7(),
payload jsonb NOT NULL
);
On older versions without uuidv7(), generate v7 values in the application and insert them.
In MySQL
MySQL has no UUID column type. Store UUIDs in BINARY(16), not CHAR(36): the text form is more than twice as large, and every secondary index in InnoDB repeats the primary key, so the waste multiplies.
CREATE TABLE invoices (
id BINARY(16) PRIMARY KEY,
total_cents BIGINT NOT NULL
);
INSERT INTO invoices (id, total_cents)
VALUES (UUID_TO_BIN('01a1c6a6-cbc1-738f-afb1-0b1b44148899'), 125000);
SELECT BIN_TO_UUID(id) AS id, total_cents FROM invoices;
MySQL's own UUID() function produces version 1 UUIDs. If you generate keys in the database, UUID_TO_BIN(UUID(), 1) reorders the time parts so they sort better. If you generate v7 in the application, insert it with plain UUID_TO_BIN(value), because v7 is already ordered.
In MongoDB
MongoDB already made this choice for you. Its default _id is an ObjectId: 12 bytes, starting with a 4-byte creation timestamp in seconds, followed by random and counter bytes. So it is time-ordered like UUID v7, smaller, and generated by the driver without asking the database.
const id = new ObjectId();
id.toString(); // e.g. '6af35de6e6d79d09693ed041'
id.getTimestamp(); // the creation time, built in
Unless you need IDs that are shared with non-Mongo systems, keep ObjectId. It also gives you a free "created at" date.
The hybrid I use most: internal integer, public UUID
For many SQL tables, the best answer is both: a BIGINT auto-increment primary key that stays internal, used for joins and foreign keys, and a separate UUID column with a unique index for anything public (URLs, API responses, webhooks).
CREATE TABLE customers (
id BIGINT AUTO_INCREMENT PRIMARY KEY, -- internal: joins, foreign keys
public_id BINARY(16) NOT NULL UNIQUE, -- external: URLs and APIs
email VARCHAR(255) NOT NULL
);
Joins stay small and fast, while nothing outside the system ever sees the sequential number. You can add a public_id column to an existing table later without touching its primary key or any foreign keys, which makes this the safest way to retrofit UUIDs into an older app.
Common mistakes
- Storing UUIDs as
VARCHAR(36)in MySQL. UseBINARY(16)and convert at the edges. - Comparing UUIDs case-sensitively.
A1B2…anda1b2…are the same UUID. Store them lowercase, which is what nearly every generator produces. - Using UUIDs as secret tokens. They are hard to guess, but they end up in URLs, logs and analytics. For password-reset links or API keys, use a dedicated random token.
- Mixing ID types across services. Choose one public ID format for your whole API and stick to it, or every integration needs special cases.
FAQ
Is UUID better than auto-increment for a primary key?
Neither is better everywhere. Auto-increment is smaller and faster for a single database. UUIDs are better when IDs are created in several places, must be merged across databases, or appear publicly. Many systems use an integer internally and a UUID publicly.
Are UUIDs slower than integers?
As primary keys, random v4 UUIDs make inserts and indexes less efficient on large, write-heavy tables, because each insert lands at a random point in the index. Time-ordered UUID v7 avoids most of that cost. Lookups by key are fast with either.
What is the difference between UUID v4 and UUID v7?
UUID v4 is random apart from its version bits. UUID v7 starts with a millisecond timestamp, so values sort by creation time, which keeps database indexes compact. Both are 128 bits and use the same 36-character text format.
Can two UUIDs ever be the same?
In theory yes; in practice no. A v4 UUID has 122 random bits, so you would need to generate billions of IDs every second for many years before a collision became likely.
Should I use UUIDs in MongoDB?
Usually not. MongoDB's default ObjectId is already unique, time-ordered and smaller than a UUID. Use UUIDs only when the ID has to match identifiers in other systems.
Try the related tools
Related articles

JWT Expired? How to Debug 401 Unauthorized Errors Step by Step
Decode the token, read the exact jsonwebtoken error, and fix expired tokens, invalid signatures, clock skew and audience mismatches.
Read article
Cron Expression Examples: 25 Schedules You Can Copy
Copy-ready cron expressions for every few minutes, daily, weekly and monthly jobs, plus the time zone and day-of-week traps that break them.
Read article
How Accurate Is IP Geolocation? What Your IP Address Reveals
IP geolocation is reliable for the country, rough for the city and never shows a house. Why, what it does reveal, and how to use it well.
Read article