Skip to content

Instantly share code, notes, and snippets.

@davidcelis
Forked from beginor/snowflake-id.sql
Last active November 6, 2022 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidcelis/53b4c38981d393e40d8e63bf886a5fee to your computer and use it in GitHub Desktop.
Save davidcelis/53b4c38981d393e40d8e63bf886a5fee to your computer and use it in GitHub Desktop.
Twitter Snowflake ID for PostgreSQL
CREATE SEQUENCE public.snowflake_id_seq;
ALTER SEQUENCE public.snowflake_id_seq OWNER TO postgres;
CREATE OR REPLACE FUNCTION public.snowflake_id()
RETURNS bigint
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
epoch bigint := 1288834974657;
seq_id bigint;
now_millis bigint;
-- the id of this DB shard, must be set for each
-- schema shard you have - you could pass this as a parameter too
shard_id int := 1;
result bigint:= 0;
BEGIN
SELECT nextval('public.snowflake_id_seq') % 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);
return result;
END;
$BODY$;
ALTER FUNCTION public.snowflake_id() OWNER TO postgres;
-- SELECT public.snowflake_id()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment