Skip to content

Instantly share code, notes, and snippets.

@anthowen
Forked from dustinrouillard/snowflake.sql
Last active January 18, 2021 09:49
Show Gist options
  • Save anthowen/9dab0b29c6349fb6b2e5b58b611cc99f to your computer and use it in GitHub Desktop.
Save anthowen/9dab0b29c6349fb6b2e5b58b611cc99f to your computer and use it in GitHub Desktop.
DB Best Practices & PostgreSQL Snowflake ID Generator Function
CREATE SEQUENCE IF NOT EXISTS public.global_id_sequence;
CREATE OR REPLACE FUNCTION id_generator(OUT result BIGINT) AS $$
DECLARE
epoch BIGINT := 1610850820000;
seq_id BIGINT;
now_millis BIGINT;
shard_id INT := 1;
BEGIN
SELECT nextval('public.global_id_sequence') % 1024 INTO seq_id;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment