Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4862 pages

Databases and servers

PostgreSQL 18 uuidv7() and NOT NULL NOT VALID: what each one does

In short

PostgreSQL 18 adds uuidv7(), a built-in function that returns time-ordered version 7 UUIDs, next to gen_random_uuid() and a new uuidv4() alias for random ones. It also lets ALTER TABLE add a NOT NULL constraint as NOT VALID, skipping the table scan, and check old rows later with VALIDATE CONSTRAINT under a SHARE UPDATE EXCLUSIVE lock.

What uuidv7() returns in PostgreSQL 18

The 18.0 release notes, from 2025-09-25, describe uuidv7() as a version 7 generator whose values are temporally sortable. The functions page spells out the layout: a Unix timestamp with millisecond precision, then a sub-millisecond timestamp, then random bits. The release announcement gives the reason people want it: timestamp-ordered UUIDs that support better caching strategies.

The function takes one optional argument, an interval called shift, that moves the embedded timestamp. Infinite intervals are refused, and the shifted time has to stay inside what the 48-bit millisecond field can hold, from 1970-01-01 UTC to roughly the year 10889. Anything outside that raises an error.

Version 18 also adds uuidv4() as an explicit name for random UUIDs. It does the same job as gen_random_uuid(), which still exists, so code that already calls gen_random_uuid() keeps working with no change. If an older server says that function is missing, the page on gen_random_uuid() failing on older PostgreSQL covers that case.

One question the docs leave open is ordering inside a single millisecond. The functions page does not promise that two calls in the same session always increase, so I would not build logic that depends on strict order between rows created at the same instant.

FunctionUUID versionSortable by timeWhat the docs say
gen_random_uuid()4NoGenerates a random UUID
uuidv4()4NoNew name in 18 for the same random UUID
uuidv7([shift])7YesUnix ms timestamp, sub-ms timestamp, random; optional shift
uuid_extract_timestamp(uuid)reads 1 or 7n/aReturns the embedded time, null for other versions
uuid_extract_version(uuid)any RFC 9562 variantn/aReturns the version number

Checked against: source 1, source 2, source 6

A worked uuidv7 example: reading the time back out

The functions page uses 019535d9-3df7-79fb-b466-fa907fa17f9e as its sample version 7 value. The first 12 hex digits, 019535d93df7, are the millisecond timestamp. In decimal that is 1,740,365,184,503 milliseconds after the Unix epoch, which is 2025-02-24 02:46:24.503 UTC. The page shows uuid_extract_timestamp() returning 2025-02-23 21:46:24.503-05 for the same value, the identical instant written in a UTC minus five zone. The 13th digit, 7, is the version, and uuid_extract_version() returns 7 for it.

Two practical points follow. Anyone who can see a version 7 key can read roughly when the row was made, because the time sits in the first 48 bits and the extraction function is built in. For public identifiers where creation time is private, a random version 4 value stays the safer default. The docs also note that the extracted time is not necessarily the exact generation time, since that depends on the generator, so treat it as an approximation and keep a real timestamp column for anything that matters.

To try values locally, the UUID generator tool makes test IDs in the browser.

CREATE TABLE events (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  payload jsonb
);
SELECT id, uuid_extract_timestamp(id), uuid_extract_version(id) FROM events;

Checked against: source 2

How NOT NULL NOT VALID works in PostgreSQL 18

In 18, column NOT NULL rules are stored in pg_constraint, so they can have names, and the release notes add that ALTER TABLE can now set them as NOT VALID. The ALTER TABLE page lists not-null alongside foreign-key and CHECK as the three constraint kinds that accept NOT VALID.

The point is the scan. Adding a constraint normally reads the whole table to prove every existing row passes, and other updates are locked out until that command commits. With NOT VALID the scan is skipped and the command can commit at once. New inserts and updates are still checked from that moment on; only the rows that were already there go unchecked until you validate.

Validation is the second step. VALIDATE CONSTRAINT scans the table but takes only a SHARE UPDATE EXCLUSIVE lock, because other sessions are already enforcing the rule on rows they write. The add step still takes ACCESS EXCLUSIVE, the default for most ALTER TABLE forms, but holds it only briefly since there is no scan.

The docs carry no example for this pairing. The statements below combine the NOT NULL column_name table constraint form from CREATE TABLE with the NOT VALID option from ALTER TABLE; run them on a copy first.

ALTER TABLE orders
  ADD CONSTRAINT orders_customer_id_not_null NOT NULL customer_id NOT VALID;
-- backfill old rows that are still NULL, in batches
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_not_null;

Checked against: source 1, source 3, source 4

NOT VALID compared with SET NOT NULL

SET NOT NULL is still there and still scans the whole table under the default ACCESS EXCLUSIVE lock, unless a valid CHECK constraint already proves the column has no NULLs, in which case the scan is skipped. That CHECK trick was the usual workaround before 18, and the walkthrough of the CHECK constraint route to NOT NULL shows it. If the column already has an invalid not-null constraint, SET NOT NULL validates it.

When the column is brand new and old rows have no value, a different problem applies, and the fix for a new required column on a populated table deals with it.

StatementScans the tableLock the docs state
ADD CONSTRAINT ... NOT NULL col NOT VALIDNoACCESS EXCLUSIVE, brief
VALIDATE CONSTRAINTYesSHARE UPDATE EXCLUSIVE
ALTER COLUMN ... SET NOT NULLYes, unless a valid CHECK proves no NULLsACCESS EXCLUSIVE (default)

Checked against: source 3

Other PostgreSQL 18 schema changes next to uuidv7

Generated columns are now virtual by default. A virtual column is computed when read and takes no storage, while STORED keeps the old compute-on-write behavior. Older DDL always had to say STORED, so existing scripts keep their meaning, but a new definition that leaves the keyword out gets a virtual column. Virtual columns cannot use a user-defined type, and their expression may use only built-in functions and types.

RETURNING can now name old and new in INSERT, UPDATE, DELETE and MERGE, so one statement can report a value before and after a change, for example RETURNING old.status, new.status. The docs say old values are normally NULL for an INSERT, except for conflicting rows in INSERT ... ON CONFLICT DO UPDATE, and new values are normally NULL for a DELETE. The aliases can be renamed when they clash with a table name.

CHECK and foreign key constraints can also be declared NOT ENFORCED, and VALIDATE CONSTRAINT throws an error on a constraint set that way.

Checked against: source 1, source 3, source 4, source 5

What to check before using these in production

A short order of work, read from the docs on 29 Nov 2026:

  • Confirm every server and replica runs 18 before any migration calls uuidv7() or adds NOT NULL NOT VALID; older servers do not have either feature.
  • Decide per table whether a creation time inside the key is acceptable.
  • Name your NOT NULL constraints so VALIDATE CONSTRAINT can target them.
  • Backfill NULLs between the add and the validate steps, then validate during a quiet period.
  • Search DDL for generated columns written without STORED if the scripts were edited for 18.
  • These pages were read on 29 Nov 2026; re-check the 18.x minor release notes before relying on them. The PostgreSQL 18 pg_upgrade changes cover getting there, the io_method and asynchronous I/O note covers the read path, and the engineering hub lists the rest.

Checked against: source 1, source 2, source 3

What else do people ask?

Is uuidv7() built into PostgreSQL 18 or an extension?

It is built in. The 18 functions page lists uuidv7() next to gen_random_uuid() and uuidv4(); uuid-ossp is only needed for other algorithms.

What is the difference between gen_random_uuid and uuidv7 in PostgreSQL 18?

gen_random_uuid() makes a random version 4 UUID. uuidv7() makes a version 7 UUID that starts with a millisecond timestamp, so values sort roughly by creation time.

Can I get the creation time back from a uuidv7 value?

Yes, uuid_extract_timestamp() returns it for version 1 and 7 UUIDs. The docs warn it may not equal the exact moment the UUID was generated.

Does adding NOT NULL NOT VALID lock the table?

Briefly. The add takes ACCESS EXCLUSIVE but skips the scan, and the later VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE, which does not block normal updates.

Are new rows checked while a NOT NULL constraint is NOT VALID?

Yes. Inserts and updates must pass from the moment it is added; only rows that existed before stay unchecked until validation.

Are generated columns virtual by default in PostgreSQL 18?

Yes. VIRTUAL is the default when neither keyword is given; write STORED to keep the value on disk.

Sources

Keep reading

Next step

Have a project in mind?

Tell me about it. A discovery call within 48 hours.