Skip to content

Instantly share code, notes, and snippets.

@thebmw
Last active May 8, 2024 19:46
Show Gist options
  • Save thebmw/d4e5c8bf57f19ec30cfbdda88361e53e to your computer and use it in GitHub Desktop.
Save thebmw/d4e5c8bf57f19ec30cfbdda88361e53e to your computer and use it in GitHub Desktop.
Postgres PL/SQL fnv1a 32 bit hash function for strings
CREATE OR REPLACE FUNCTION public.hash_fnv1a_32(
p_data character varying,
p_init bigint DEFAULT '2166136261'::bigint,
p_prime bigint DEFAULT 16777619)
RETURNS bigint
LANGUAGE 'plpgsql'
COST 100
STABLE PARALLEL SAFE
AS $BODY$
DECLARE
v_hval bigint;
ch char;
BEGIN
v_hval := p_init;
FOREACH ch IN ARRAY regexp_split_to_array(p_data, '')
LOOP
v_hval := v_hval # ASCII(ch);
v_hval := (v_hval * p_prime) % 4294967296;
END LOOP;
RETURN v_hval;
END;
$BODY$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment