How to create a guid in PostgreSQL

How do I create a Windows-formatted GUID in Postgres 9.0+?

I tried the function

CREATE or REPLACE FUNCTION public.getguid() RETURNS varchar AS $BODY$ 
DECLARE 
  v_seed_value varchar(32); 
BEGIN 
  select 
    md5( 
      inet_client_addr()::varchar || 
      timeofday() || 
      inet_server_addr()::varchar || 
      to_hex(inet_client_port()) 
    ) 
  into v_seed_value; 

  return (substr(v_seed_value,1,8) || '-' || 
          substr(v_seed_value,9,4) || '-' || 
          substr(v_seed_value,13,4) || '-' || 
          substr(v_seed_value,17,4) || '-' || 
          substr(v_seed_value,21,12)); 
END; $BODY$ LANGUAGE 'plpgsql' VOLATILE SECURITY DEFINER;

      

of

http://postgresql.1045698.n5.nabble.com/newid-in-postgres-td1879346.html

Tried

select getguid()
union all
select getguid()

      

but it returns the same values

"c41121ed-b6fb-c9a6-bc9b-574c82929e7e"
"c41121ed-b6fb-c9a6-bc9b-574c82929e7e"

      

How do I fix this so that unique strings are returned?

+3


source to share


1 answer


PostgreSQL has an extension uuid-ossp

that comes with standard distributions and has 5 standard algorithms for generating uuid

s. Note that a guid

is Microsoft's version uuid

, conceptually the same.

CREATE EXTENSION "uuid-ossp";

      

Then:



SELECT uuid_generate_v4();

      

Note also that after installing the extension, PostgreSQL has an actual binary type uuid

of 16 bytes. Working with a binary type is much faster than working with a text equivalent and takes up less space. If you want the string version, you can simply translate it to text

:

SELECT uuid_generate_v4()::text;

      

+10


source







All Articles