PostgreSQL has a native uuid data type and, since version 13, a built-in gen_random_uuid() function that returns a random version 4 UUID. No extension is required on modern Postgres.
The examples show generating a UUID directly and using one as an auto-populated primary key.
Generate a random UUID
Call gen_random_uuid() in any query. It returns a value of the native uuid type.
SELECT gen_random_uuid();
-- 9b2e4f1a-3c6d-4e58-9f0a-1b2c3d4e5f60UUID primary key with a default
Set the column type to uuid and default it to gen_random_uuid() so every inserted row gets an identifier automatically.
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL
);
INSERT INTO users (email) VALUES ('a@example.com')
RETURNING id;Older Postgres and the uuid-ossp extension
On Postgres versions before 13, enable the uuid-ossp extension and use uuid_generate_v4(). gen_random_uuid() is preferred on current versions.
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SELECT uuid_generate_v4();Frequently asked questions
- Do I need an extension to generate UUIDs in PostgreSQL?
- Not on PostgreSQL 13+. gen_random_uuid() is built in. Older versions need the uuid-ossp extension and uuid_generate_v4().
- How do I make a UUID primary key auto-generate in Postgres?
- Declare the column as uuid PRIMARY KEY DEFAULT gen_random_uuid(); each insert then gets a UUID automatically.
- Should I store UUIDs as text in Postgres?
- No. Use the native uuid type. It stores the value in 16 bytes and is more efficient than text.
