It's incredibly simple to use the uuid data type in PostgreSQL!
First we need to enable the uuid-ossp extension by executing the following SQL:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Now the uuid
data type is available for us to use! Let's try using it as our primary key in a table.
CREATE TABLE users (
id uuid PRIMARY KEY NOT NULL DEFAULT uuid_generate_v4(),
name text NOT NULL
);
Notice that we're generating default ids by calling the uuid_generate_v4()
function.
Let's test it out by inserting a record.
INSERT INTO users (name) VALUES ("Sean Huber");
We can verify that it worked with a simple SELECT * FROM users
!
id | name
--------------------------------------+-------------------
cf5c79cd-8a8d-4afd-8091-ef93f662a44d | Sean Huber
(1 row)