postgres unique id column management

 UUID function in postgres:


UUID is a unique identifier used in primary key columns as an alternative to the sequences. You can create a table column with UUID datatype and auto generate the values for the column to ensure uniqueness.

See the example below.


Step 1: Create the extension as below to use the uuid generator function.

mytestdb=# CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE EXTENSION


Step 2: Create table with uuid column

mytestdb=# create table ytable (id uuid, name varchar(20));

CREATE TABLE

mytestdb=# select * from ytable;

 id | name 

----+------

(0 rows)


Step 3: Insert new values using the uuid generator during insert:


mytestdb=# insert into ytable values (uuid_generate_v4(), 'aaa');

INSERT 0 1

mytestdb=# insert into ytable values (uuid_generate_v4(), 'aaa');

INSERT 0 1

mytestdb=# insert into ytable values (uuid_generate_v4(), 'aaa');

INSERT 0 1

mytestdb=# insert into ytable values (uuid_generate_v4(), 'aaa');

INSERT 0 1

mytestdb=# select * from ytable;

                  id                  | name 

--------------------------------------+------

 3dffa4ba-8491-44f1-8573-eccd9f116a62 | aaa

 cc449a40-4d4a-4641-8abf-26fc147aa656 | aaa

 1c2d86e4-ff10-415b-b855-c701e16f4e42 | aaa

 375b94ab-88eb-4f18-8495-3e332316f09b | aaa

(4 rows)


Comments

Popular posts from this blog

PostgreSQL Tools

Move postgreSQL server data to new Folder Location

PostgreSQL for Oracle DBAs