AI Hints
Home›PostgreSQL Tutorial›Enums, UUIDs and Ranges
PostgreSQL · Lesson 47 of 120

UUIDs

IDs safe to share.

⏱ 2 min read▶ Video at 40:56🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Order one thousand and one tells a competitor how many orders you have. And a customer could guess order one thousand and two. UUIDs are long random IDs that can't be guessed.

  • Guessable IDs
  • Leak your size
  • UUIDs

UUID primary keys

UUID v seven is new in Postgres eighteen. It's random, but starts with the time, so new IDs sort in order, which keeps indexes fast. Run it. Two long, unguessable IDs.

query.sqlsql
CREATE TABLE gift_cards (
  id     uuid PRIMARY KEY DEFAULT uuidv7(),
  amount numeric(6,2) NOT NULL
);
INSERT INTO gift_cards (amount) VALUES (25), (50) RETURNING *;
Output
CREATE TABLE
                  id                  | amount
--------------------------------------+--------
 01a1db3d-4221-70db-bcb2-5f6be76fc16b |  25.00
 01a1db3d-4221-73df-bf84-8bd016fbcdc5 |  50.00
(2 rows)

INSERT 0 2
Also uses _empty
1

Which ID?

Identity integers are small and fast, great inside your system. UUIDs are safe to show in URLs and APIs. Prefer version seven over random version four, because it's index friendly.

keyvalue
integer identityinternal, fast
UUIDpublic, unguessable
uuidv7()time-ordered, PG 18
gen_random_uuid()v4, random

Summary

UUIDs are unguessable IDs, and version seven keeps them in time order. Next, range types.

Key takeaways
  • uuid
  • uuidv7()
  • Unguessable
Next up: Range Types — from and to