Hashing a String to a Numeric Value in PostgreSQL

前端 未结 4 1361
情歌与酒
情歌与酒 2020-12-07 23:16

I need to Convert Strings stored in my Database to a Numeric value. Result can be Integer (preferred) or Bigint. This conversion is to be done at Database side in a PL/pgSQL

4条回答
  •  一向
    一向 (楼主)
    2020-12-07 23:41

    Just keep the first 32 bits or 64 bits of the MD5 hash. Of course, it voids the main property of md5 (=the probability of collision being infinitesimal) but you'll still get a wide dispersion of values which presumably is good enough for your problem.

    SQL functions derived from the other answers:

    For bigint:

    create function h_bigint(text) returns bigint as $$
     select ('x'||substr(md5($1),1,16))::bit(64)::bigint;
    $$ language sql;
    

    For int:

    create function h_int(text) returns int as $$
     select ('x'||substr(md5($1),1,8))::bit(32)::int;
    $$ language sql;
    

提交回复
热议问题