How to generate 12 digit unique number in redshift?

自闭症网瘾萝莉.ら 提交于 2019-12-11 05:42:46

问题


I have 3 columns in a table i.e. email_id, rid, final_id.

Rules for rid and final_id:

  1. If the email_id has a corresponding rid, use rid as the final_id.
  2. If the email_id does not have a corresponding rid(i.e.rid is null), generate a unique 12 digit number and insert into final_id field.

How to generate 12 digit unique number in redshift?


回答1:


From Creating a UUID function in Redshift:

By default there is no UUID function in AWS Redshift. However with the Python User-Defined Function you can easily create a UUID function in Redshift.

If you want random UUID:

CREATE OR REPLACE FUNCTION public.fn_uuid()
RETURNS character varying AS
' import uuid
 return uuid.uuid4().__str__()
 '
LANGUAGE plpythonu VOLATILE;

If you want sequential UUID :

CREATE OR REPLACE FUNCTION public.fn_uuid()
RETURNS character varying AS
' import uuid
 return uuid.uuid1().__str__()
 '
LANGUAGE plpythonu VOLATILE;



回答2:


I had the same issue for ages but I wasn't comfortable to use a custom function to generate UUID in Redshift either.

Often in Redshift tables, a combination of columns are unique. md5() built-in function in Redshift can help to generate unique hashes based on these combination of columns.

Disclaimer: it guarantees unique id only if the combination of columns are guaranteed to be unique.

Lets assume col1 and col2 together are unique for a table. Then

`select md5(col1::varchar || col2::varchar)`

can guarantee a unique hash. Added advantage is the speed when using this in JOINs.

Reference: https://blog.fishtownanalytics.com/the-most-underutilized-function-in-sql-9279b536ed1a



来源:https://stackoverflow.com/questions/46578889/how-to-generate-12-digit-unique-number-in-redshift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!