How to Generate a UUID in PostgreSQL

    Use gen_random_uuid() for random UUID primary keys, with notes on the uuid type and defaults.

    Need a UUID right now? Generate one instantly in your browser.

    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.

    sql
    SELECT gen_random_uuid();
    -- 9b2e4f1a-3c6d-4e58-9f0a-1b2c3d4e5f60

    UUID 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.

    sql
    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.

    sql
    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.

    Cookie Consent

    We use cookies to enhance your experience on our website. By accepting, you agree to the use of cookies in accordance with our Privacy Policy.