UUIDv7 primary keys in PostgreSQL 18

PostgreSQL 18 ships uuidv7(), which makes UUID primary keys sortable by creation time. This page explains when that beats bigint identity or random UUIDv4 keys, and what changing keys costs.

On this page

UUIDv7 primary keys in PostgreSQL 18: when they fit your schema

If your team is designing or changing primary keys in a self-hosted PostgreSQL 18 database, the choice comes down to three options: a bigint identity column, a random UUIDv4 and a time-ordered UUIDv7. PostgreSQL 18 added uuidv7(), which generates version 7 UUIDs that sort by creation time, so you no longer need an application library to get them. The right answer depends on how the index behaves under your insert pattern, what the key reveals to anyone who sees it, and how much work it takes to change keys on tables that already hold data.

The release notes list three UUID generators: uuidv7() for time-ordered keys, gen_random_uuid() for random version 4 keys, and uuidv4() as an alias for the random generator. Random keys scatter inserts across the whole primary key index, which tends to cause more page splits and cache churn on large tables. Time-ordered keys append near the right edge of the index, closer to how a bigint sequence behaves. Teams usually need this when they expect high insert volume, when they want to avoid sorting by a separate timestamp column, or when they are standardizing keys across services that generate IDs before the database sees them.

Before you pick one, confirm what a UUIDv7 key exposes. Its embedded timestamp reveals approximately when a row was created, which may matter for customer-facing identifiers, invoice numbers or any record count that outsiders can infer from ordering. A bigint identity reveals the row count and rough order, and a random UUIDv4 reveals neither. Check the policy for each exposed table with your security and privacy owners, and check whether the keys appear in URLs, logs or exported files.

If you are changing keys on an existing table, the cost sits in the migration rather than the function call. Adding a UUIDv7 column, backfilling it in batches, rewriting foreign keys and updating every application that caches IDs each take planning and testing. Confirm the exact behavior of uuidv7() and the index guidance against the PostgreSQL 18 release notes and the UUID functions documentation before you write migration scripts, and test the chosen key type on a copy of your largest table.

Comparing bigint identity, UUIDv4 and UUIDv7 keys

This table compares the three common primary key choices for PostgreSQL tables across index behavior, storage, time exposure, distributed generation and migration effort. Read each row as a question to answer for your own tables, then test the storage and index claims against your data before deciding.

Factorbigint identityUUIDv4 (random)UUIDv7 (time-ordered)
Index locality on insertsInserts append to the right edge of the B-tree, so new pages stay hot in cache.Values are random, so inserts land across the whole index and touch many pages.Values increase with time, so inserts mostly append like bigint, though not exactly the same.
Storage per key8 bytes.16 bytes, with the index entry and any foreign key columns growing accordingly.16 bytes, the same width as UUIDv4, so the per-row cost is the same as UUIDv4.
Exposure of creation timeReveals only insert order and approximate volume if values are sequential and guessable.Reveals no creation time from the value.Embeds a millisecond timestamp, so anyone holding an ID can estimate when the row was created.
Generation without a central databaseNeeds the database or a shared sequence strategy, and ranges must be split across nodes to avoid collisions.Generated by any client or service with no coordination.Generated by any client or service with no coordination, with ordering roughly preserved across nodes.
Migration effort for existing tablesUsually the lowest in a bigint-keyed system, but changing an existing key type still means rewriting foreign keys and application code.Changing a bigint key to UUID touches every referencing table, API contract and index, so plan a staged backfill.Same migration path as UUIDv4, with the added question of whether leaking creation time is acceptable for each table.
Built-in generation in PostgreSQL 18Provided by identity columns and sequences.Available through gen_random_uuid() and uuidv4().Available through uuidv7(), added in PostgreSQL 18.
Best fitHigh-volume internal tables where keys stay inside the database and are not exposed in URLs.Public identifiers where creation time must stay hidden and insert locality is not a bottleneck.Public identifiers that also need time-ordered inserts, such as event or order tables, when the time disclosure is acceptable.

How time-ordered keys affect B-tree index locality

The main index effect of the key choice is where new rows land in the primary key B-tree. A random UUIDv4 value, which gen_random_uuid() and uuidv4() produce, can sort anywhere in the index, so each insert touches a leaf page chosen at random across the whole index. A time-ordered UUIDv7 value from uuidv7() starts with a timestamp, so consecutive inserts sort close together and append near the right edge of the index. A bigint identity column also appends at the end, so UUIDv7 is the closer of the two UUID options to that pattern.

Qualitatively, the random pattern hurts in two ways. Because the leaf pages that receive writes are spread across the index, the working set the database needs in shared buffers and the operating system cache grows with the size of the index, not with the rate of new rows. Random placement also causes more page splits, and those splits leave partly filled pages behind, which makes the index larger and less dense. Append-style inserts keep the active leaf pages few and hot, and they split less often. The size of these effects depends on index size, available memory, row width and write rate, so the gap may be small for a table that fits comfortably in memory and large for one that does not.

Confirm the impact on your own workload before choosing a key type for a large table. Load a representative data set with each candidate key, then compare index size with pg_relation_size and pg_indexes_size, watch buffer hit ratios and write latency under realistic concurrency, and read EXPLAIN (ANALYZE, BUFFERS) output for the insert and lookup queries your application runs most. Also check that the timestamp in UUIDv7 is acceptable to expose, because it reveals approximate creation time, which is covered in the next section. The PostgreSQL 18 release notes describe the new function, and your own benchmark should decide the trade-off.

What a creation timestamp in the key exposes

A UUIDv7 carries its creation time in the clear, so anyone who sees the key can read it. The cards below cover what that exposes, how ordering leaks volume, and why keys must never stand in for access control.

Creation time is readable from the ID

A UUIDv7 encodes a millisecond Unix timestamp in its leading bits, so anyone holding an ID can decode when that row was created without querying the database. The timestamp is not encrypted or salted. Before you adopt uuidv7() for a table, ask whether row creation time is something customers, partners or competitors should learn from a URL or API response. If it is, keep the key but avoid exposing it in public identifiers.

UUID functions docs

Ordering leaks volume and growth rate

Because keys increase over time, two IDs obtained weeks apart reveal how many records were created between them. A competitor who creates accounts periodically can estimate your customer count, order rate or growth curve from sequential identifiers. This matters most for customer-facing IDs in invoices, order numbers and public links. Check whether any endpoint returns IDs in a way that lets an outsider sample them over time.

IDs are not secret tokens

A primary key identifies a row. It is not a credential, and it should never grant access by itself, whether it is a bigint, a UUIDv4 or a UUIDv7. Systems that accept a record ID in a URL and return data without checking the caller's rights have an authorization defect regardless of key format. Treat keys as identifiers that appear in logs, emails, browser history and third-party tools.

Sequential patterns aid enumeration

When authorization is weak, predictable keys make enumeration cheap. An attacker who finds one valid ID can generate neighboring candidates, since UUIDv7 values created close together share their leading bits and differ mainly in the random suffix. The random portion still makes brute force impractical for most designs, but it is not a substitute for checks. Test whether each object endpoint returns 403 or 404 for IDs belonging to other tenants or users.

Pair keys with access checks

The control that matters is an authorization check on every read and write, enforced by the application or by PostgreSQL policies such as row-level security. Confirm that each query filters by the caller's tenant or owner, and that deny responses do not reveal whether an ID exists. Use the key format you choose for joins and indexing, and let access rules decide who may read the row. Review this design with your security team before go-live.

Adopting uuidv7() in a PostgreSQL 18 schema

This sequence takes a new table from confirming the server version to a tested schema that uses uuidv7() defaults, so the team knows the keys sort by creation time, the indexes stay manageable and the application code accepts the values.

  1. Confirm the server runs PostgreSQL 18

    The database administrator runs SELECT version(); against every server that will hold the table, including each standby and any staging copy. The function uuidv7() exists only in PostgreSQL 18, so an older server will reject the default at table creation or, worse, fail later during a failover to a standby that runs a different major version. The step is done when every node reports 18.x and the team has recorded the minor version so patching can be planned against the supported release list in the versioning policy.

  2. Set the column default to uuidv7()

    The schema owner declares the primary key as uuid PRIMARY KEY DEFAULT uuidv7() in the migration, using a review step for the DDL. Teams that already use bigint identity columns should decide first whether this table needs a UUID at all, since the choice affects foreign keys and any external system that stores the key. The step is done when \d tablename shows the default and a test insert returns a value whose first 48 bits match the current time, which confirms the keys are time-ordered.

  3. Decide where keys are generated

    The architecture owner chooses whether the database or the application generates each key. Database defaults keep one source of truth and work for every client that writes to the table, while application-side generation lets the service know the ID before the insert, which helps with batching and some event designs. Whichever path is chosen, the team should write it down and confirm that no code path generates keys with a different algorithm, because mixed generators can break the ordering benefit. The step is done when a written decision exists and a grep of the codebase finds no other UUID generator on that table.

  4. Test inserts and index size on realistic data

    The performance owner loads a copy of production-like volume into a staging server and compares the primary key index for the uuidv7() default against the bigint or uuidv4 option under the same insert pattern. Measure index size with pg_relation_size and pg_indexes_size, and watch insert latency and buffer behavior during the load. The benchmark must use realistic row counts and write rates, because small tables hide the effects of index locality. The step is done when the team has a measured comparison it can show in its design review, not an estimate.

  5. Check driver and ORM support for UUID columns

    The application developers run the existing data access layer against the staging schema and confirm that each driver and ORM maps the uuid type to the language's native UUID type and serializes it as a canonical string. Pay attention to older connectors, JSON serialization in APIs and any code that validates identifiers with a fixed pattern. The step is done when integration tests create, read, update and join rows through every service that touches the table, and no component truncates, reorders or rejects the values.

  6. Confirm the exposure of creation time

    The security or privacy reviewer checks what the key reveals. A uuidv7() value encodes a millisecond timestamp, so anyone who can see identifiers can estimate when a record was created and, by comparing values, roughly how many records were created in a period. The reviewer records whether that is acceptable for the table, and decides whether identifiers appear in public URLs, export files or logs. The step is done when the decision is documented alongside the data classification of the table.

  7. Record the schema standard and verify in a rehearsal

    The platform owner adds the agreed pattern to the migration standards, including the default, the generator decision and the exposure note, then runs the migration in a rehearsal environment on the same PostgreSQL 18 minor version planned for production. The team confirms the table, default, index and application tests pass in the rehearsal, and that a restore from backup returns the same default and index definitions. The step is done when the rehearsal output is attached to the change record and production can follow the same script.

Which key type fits which situation

When one PostgreSQL primary takes most inserts and the application can rely on the database to assign keys, bigint identity columns are the simplest option. They are small, compare quickly and produce compact B-tree indexes. UUIDv7 keeps this model workable while removing most of the locality problem that random UUIDv4 creates, because new values sort near the most recent inserts. UUIDv4 values land at random positions across the primary key index, which tends to increase page splits, cache churn and write amplification as tables grow.

  • Index size: a UUID is 16 bytes against 8 for bigint, so primary keys and every secondary index that carries them grow accordingly.
  • Insert locality: time-ordered values append near the right edge of the index, while random values scatter writes across it.
  • Sequence contention: identity columns are cheap in one database, but they become a shared point when you add writers elsewhere.
  • Measured effect: the difference depends on table size, buffer cache and write rate, so benchmark with your own schema before deciding.

Before you choose, ask your team to run a representative insert and index-size test on the largest table you expect to have.

Limits to confirm before you commit

UUIDv7 keys look like a drop-in change, but the effect depends on the drivers, ORMs, reporting tools and replicas around the database. The cards below are items to verify in your own environment before you choose a key type for a table, and none of them is settled by the PostgreSQL documentation alone.

Driver, ORM and BI tool support

Check that your database driver, ORM and BI tools map the PostgreSQL uuid type to a native type in your language and do not convert it to text. Some tools generate their own UUID values on insert, which can bypass uuidv7() and mix generation methods in one column. Test a read, write and filter on a sample table before any migration, and confirm how each tool displays and sorts UUID values.

UUID functions docs

Server version and function availability

uuidv7() exists only on PostgreSQL 18 and later. Confirm the server version in each environment, including development, staging, replicas and any managed or packaged builds, before you write a default that calls the function. A schema that depends on it will fail to deploy on an older server, so pin the version in your migration tooling and your deployment manifests.

PostgreSQL 18 release notes

Foreign keys and referencing tables

Every table that references the new key needs a column of the same type, and the foreign key constraints must be rebuilt after the change. Check how your application creates child rows and whether any service stores these IDs as text, since a text copy will not match a uuid column without a cast. Plan the order of key changes across related tables so that no constraint points at a column that has not been converted.

Replication and logical copies

Confirm how the new key type behaves on standbys, logical subscribers and any downstream system that replicates these tables. Check that every subscriber runs a PostgreSQL version that understands the type, and that the replication setup carries sequences and generated defaults as you expect. Run a test failover and a test subscription before you rely on the design in production.

UUID index size on your data

A 128-bit UUID is wider than a bigint, so primary key and secondary indexes grow, and that growth multiplies across every index that includes the key. Measure index size and cache hit rates on a copy of your largest tables, comparing bigint, UUIDv4 and UUIDv7 with the same row counts. Your own row volume, index count and memory will decide whether the difference matters.

Creation time exposure

A UUIDv7 value carries a timestamp, so anyone who sees an identifier can infer when the record was created. Decide whether that is acceptable for each table, especially where identifiers appear in URLs, exports, logs or public APIs. Review your privacy and access policies with the data owners, and consider a separate public identifier if creation timing is sensitive.

Questions teams ask before changing primary keys

Should we switch existing tables from bigint or UUIDv4 keys to UUIDv7?

Only when the benefits justify rewriting keys that other systems already depend on. Switching is most sensible for new tables, or for tables where random UUIDv4 keys are causing measurable index bloat and cache misses. For tables that work well with bigint identity columns, the migration risk usually outweighs the gain. Start by listing which tables have high insert rates, which keys are shared with external systems, and which keys appear in logs, URLs and APIs, then decide table by table.

What does the migration effort depend on?

Effort follows the shape of the key graph more than the row count alone. The main drivers are:

  • Table size: backfilling and rewriting millions of rows takes longer and needs a planned window.
  • Foreign key count: every referencing column, index and constraint must change in step.
  • Application changes: ORMs, serializers, API contracts, caches, message payloads and analytics jobs that assume integer keys.
  • External consumers: partners or internal tools that store the old identifiers.

A table with few inbound references is a small change. A core table referenced from many services is a coordinated project.

Can our own team make this change without a partner?

Often yes, if the team has someone comfortable with PostgreSQL schema changes, a tested rollback plan and staging data that resembles production. The work is mostly careful sequencing: add the new column, backfill it in batches, add a unique index, switch foreign keys, then update the application. Teams without much migration experience, or with many services that depend on the keys, often find an outside review of the plan useful. The question to answer honestly is whether someone can own the change for the full duration, including the cleanup after cutover.

How long does a primary key migration take?

No duration can be stated without the schema and the system around it. The timeline depends on table size, the number of foreign keys, how many applications read the keys, and how much downtime or write blocking the business accepts. Ask for a written plan that separates preparation, backfill, cutover and cleanup, and that states which steps run online and which need a maintenance window. Be cautious about any estimate given before someone has inspected the actual schema.

What do we need to provide for the work?

Plan to provide read access to the schema and foreign key definitions, a list of services and jobs that read or write each key, a staging environment with a copy of production-sized data, and a named owner who can approve the cutover. You also need an agreed window for the final switch, and a restore point you have tested. Missing inventory of consumers is the most common reason these projects slow down, so it is worth completing before any quote is compared.

Does changing the key type expose creation time to users?

Yes. A UUIDv7 value embeds a millisecond timestamp in its leading bits, so anyone who sees the identifier can estimate when the row was created. This matters for public URLs, invitation links, and tenant or customer identifiers that should not reveal growth rate or ordering. If that exposure is a concern, keep a separate public identifier, or use UUIDv4 for externally visible keys while using UUIDv7 internally. Confirm the classification of each exposed identifier with your data owner.

Does the migration affect our compliance evidence?

It can. A key change alters schema, audit logs and possibly the way records are traced across systems, so the change record should show what changed, when, who approved it and how it was tested. Keep the rollback plan and restore test results with the change ticket. Your auditors or certification body decide what evidence is sufficient for your scope. DeployOpen can prepare the change documentation and control evidence, but does not issue audit reports or attestations.

Operating UUIDv7 keys safely in production

Treat a key type change as an operational change, not only a schema change. Before go-live, run a full backup and restore test on a copy that contains UUIDv7 keys, and confirm that foreign keys, sequences used by other tables and any application code that assumes bigint values still behave after restore. Check the restore procedure itself as well: your backup tool must capture the uuid column type and any default expressions that call uuidv7(), and the restored database must run the same PostgreSQL 18 minor release or a later one. Confirm the exact function list and behavior for your build in the PostgreSQL 18 release notes before writing restore runbooks around it.

Monitor index growth on every table that switches key types. Time-ordered keys usually cluster new inserts at the right edge of the primary key index, but the index still stores 16-byte values where a bigint uses 8 bytes, so measure index size and bloat against a baseline taken before the change. Watch for the pattern over several weeks of production traffic, not a single load test. Alert on index size growth per table and on the ratio of index size to table size, and review those numbers each time you add a secondary index on a UUID column.

Decide what the key reveals before it appears in logs, API responses and URLs. A UUIDv7 value embeds a millisecond creation timestamp, so anyone who sees the key can estimate when the row was created and, across sequential keys, roughly how fast records arrive. Review where keys appear in access logs, error traces, webhooks and public endpoints, and decide whether that disclosure is acceptable for each resource. Then test authorization directly: request another tenant's object by its ID, confirm the request is denied by policy (for example, row-level security or an explicit ownership check in the API), and never rely on the unguessability of a UUID as the access control.

How DeployOpen scopes and delivers PostgreSQL schema work

DeployOpen treats the choice of primary key as a schema decision with operational consequences, so we scope it before any table changes. We plan the key type, the index and migration approach, and the verification work in writing, then build and hand over the result in infrastructure you control.

How we scope

  • Inventory the tables, foreign keys, indexes and application code that depend on the current key type.
  • Agree in writing whether new tables use bigint identity, uuidv4 or uuidv7 and where each applies.
  • Define what the written scope covers, including the PostgreSQL 18 target, test environments and the migration window.

How we build

  • Create the new key definitions with uuidv7() as the default in a test copy of your schema first.
  • Measure index size and insert behavior on representative data before changing production tables.
  • Backfill and swap keys in batches with rollback steps written down for each table.

How we hand over

  • Deliver the migration scripts, schema diagrams and a record of every decision on key types.
  • Document what creation time exposure means for each table and how the application should treat it.
  • Walk your engineers through the runbook and confirm they can repeat the migration without us.

How we support

  • Offer ongoing support for schema changes and PostgreSQL upgrades as a retainer, if your team wants it.
  • Retest key-related queries and indexes after each PostgreSQL minor or major release.
  • Confirm with your own environment and the PostgreSQL 18 release notes before relying on any behavior not covered in scope.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.