The Wild

Migrate PostgreSQL Primary Key from UUIDv4 to UUIDv7

· 4 min read · Mammals

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks through converting an existing PostgreSQL primary key column from UUIDv4 (random) to UUIDv7 (time-ordered). The main benefit is improved index performance: UUIDv7 values are sequential over time, reducing index fragmentation and page splits compared to random UUIDv4. You’ll need a way to generate UUIDv7 values (e.g., a PostgreSQL extension like pg_uuidv7 or a client-side library) and a plan to handle foreign key references.

What You'll Need

  • PostgreSQL 13 or later (for ALTER TABLE ... ALTER COLUMN TYPE with a USING clause).
  • Access to a UUIDv7 generator: either install the pg_uuidv7 extension (if available for your version) or use a client-side library (e.g., Python's uuid6, Node's uuid package with v7 support).
  • Write access to the database and ability to run migrations (e.g., psql or a migration tool).
  • Backup of your database before starting.

Step-by-Step

  1. Backup your database. Run pg_dump yourdb > backup.sql or use your preferred backup method. This is non-negotiable; a failed migration can corrupt data.
  2. Ensure UUIDv7 generation is available. If using the pg_uuidv7 extension, install it: CREATE EXTENSION IF NOT EXISTS pg_uuidv7; (requires superuser). If not, prepare to generate UUIDv7 values in your application code during the migration.
  3. Identify all tables and foreign keys referencing the primary key. Run a query against information_schema or use pg_constraint to list all foreign key constraints that point to the target table's primary key. You'll need to update or temporarily drop these constraints.
  4. Plan the migration order. For each referencing table, you will need to change the foreign key column type to UUID (if it isn't already) and then update the values to match the new UUIDv7 values. The safest order: update child tables first, then the parent table.
  5. For each child table: Add a new column of type uuid (if not already), then populate it with the corresponding new UUIDv7 values. You can generate a mapping in a temporary table: CREATE TEMP TABLE mapping AS SELECT old_uuid, gen_random_uuid_v7() AS new_uuid FROM parent_table; (if using extension) or generate in application code. Then update child table: UPDATE child_table SET new_fk_col = mapping.new_uuid FROM mapping WHERE child_table.fk_col = mapping.old_uuid; After that, drop the old foreign key column and rename the new one, or just alter the existing column type and update values in place.
  6. Change the primary key column type. If the primary key column is already uuid, you can alter it to use UUIDv7 values: ALTER TABLE parent_table ALTER COLUMN id TYPE uuid USING (gen_random_uuid_v7()); (if using extension) or generate values in application code. But note: this will generate a new UUID for every row, so you must first update all child references to match. A safer approach: create a new column, populate it with UUIDv7 values, update child tables, then drop the old column and rename the new one.
  7. Recreate foreign key constraints. After updating all values, re-add the foreign key constraints with the new column types.
  8. Test thoroughly. Run queries to verify that all references are intact and that the primary key is unique.

Common Mistakes

  • Forgetting to update child tables before the parent. If you change the parent's primary key values first, foreign key constraints will fail.
  • Using ALTER COLUMN TYPE without a USING clause that generates UUIDv7. This will either fail or convert to the same random UUIDv4 values, defeating the purpose.
  • Not dropping foreign key constraints before altering column types. PostgreSQL will block the alteration if constraints are present.
  • Assuming UUIDv7 is universally supported. The pg_uuidv7 extension is not part of core PostgreSQL; you must install it separately.

Tips

  • Perform the migration during a maintenance window to avoid concurrent writes.
  • Use a temporary mapping table to ensure referential integrity during the switch.
  • If you have a very large table, consider batching the updates to avoid long locks.
  • After migration, run ANALYZE on the affected tables to update statistics.
  • Test the migration on a staging copy first.

Troubleshooting

  • “function gen_random_uuid_v7() does not exist” – The extension is not installed. Install it or use a client-side generator.
  • Foreign key violation during update – You likely updated the parent before the child. Rollback and reorder.
  • Lock timeout – If the table is large, the update may take long. Increase lock_timeout or batch the updates.
  • Data type mismatch – Ensure all related columns are of type uuid before altering. If they are varchar, cast them first.
  • Index fragmentation persists – After migration, run REINDEX on the primary key index to rebuild it with the new ordered values.

Frequently Asked Questions

Why migrate from UUIDv4 to UUIDv7?

UUIDv7 values are time-ordered, so new rows are appended to the index rather than inserted randomly. This reduces index bloat and improves write performance.

Can I convert existing UUIDv4 values to UUIDv7 without changing them?

No, the values must be regenerated. UUIDv7 encodes a timestamp, so you cannot derive it from an existing random UUID.

Will this break my foreign keys?

Only if you don't update them. You must update all referencing columns to match the new primary key values.

Is there a built-in UUIDv7 function in PostgreSQL?

No, as of PostgreSQL 16, there is no core function. You need the pg_uuidv7 extension or a client-side generator.

Can I do this without downtime?

It's difficult. The safest approach involves a maintenance window. You can minimize downtime by using a new column and a trigger to backfill, but that's complex.

What if I have a composite primary key?

This guide assumes a single-column primary key. For composite keys, you'll need to adapt the mapping and update logic accordingly.