How to Generate UUIDs in PostgreSQL

Generate UUIDs in PostgreSQL with gen_random_uuid() for v4-style values and uuidv7() on PostgreSQL 18 or newer when you want better index locality.

Recommendation: use UUID v4 when you want broad compatibility. Use UUID v7 when your PostgreSQL version supports it and you want better index locality.

How to generate UUID v4 in PostgreSQL

SELECT gen_random_uuid();

This is commonly available through pgcrypto or newer PostgreSQL packaging that exposes the function directly.

How to generate UUID v7 in PostgreSQL

SELECT uuidv7();

Check your PostgreSQL version first. uuidv7() is built in on PostgreSQL 18 and later, so older deployments still need an application-side fallback.

Native support notes

  • PostgreSQL natively supports the UUID data type regardless of how values are generated.
  • Generation functions and extension requirements vary by version.
  • uuidv7() is built in on PostgreSQL 18 and later.
  • Separate storage support from generation support when documenting UUID behavior.

Practical notes

  • UUID v4 is easy to adopt and widely portable.
  • UUID v7 can reduce index fragmentation compared with random inserts.
  • See database performance and indexing before choosing a primary key strategy.

Frequently Asked Questions

UUID storage is native, but generation functions depend on version and installed extensions.

No. uuidv7() is built in on PostgreSQL 18 and later, so verify the exact release you deploy before depending on it.

Learn more

These articles expand on related concepts, formats and practical considerations.

By using this site, you agree to our Privacy Policy and Terms of Service. You are not permitted to use the GUIDs (also known as UUIDs) generated by this site or use any other content, services and information available if you do not agree to these terms.
Disclaimer: All information is provided for general educational and technical reference only. While we aim to keep the content accurate, current and aligned with published standards, no guarantees are made regarding completeness, correctness or suitability for any specific use case.
GUID specifications, best practices, security guidance, database behavior and ecosystem conventions (including cloud platforms and identifier formats) may change over time or differ by implementation. Examples, recommendations and comparisons are illustrative and may not apply universally.
This content should not be considered legal, security, compliance or architectural advice. Before making critical design, security or production decisions, always consult the latest official standards and vendor-specific documentation.
Always evaluate behavior in your own environment.
Standards Compliance: The GUIDs generated by this site conform to RFC 4122 and RFC 9562 specifications whenever possible, using cryptographically secure random number generation.