Skip to content

Instantly share code, notes, and snippets.

@danielhutchinson
Created February 16, 2015 21:07
Show Gist options
  • Save danielhutchinson/b2647c10f9c7ac661fb7 to your computer and use it in GitHub Desktop.
Save danielhutchinson/b2647c10f9c7ac661fb7 to your computer and use it in GitHub Desktop.
A uniqe ID generator for PostgreSQL (blatantly stolen from instagram)
CREATE OR REPLACE FUNCTION uniq_id(OUT result bigint) AS $$
DECLARE
our_epoch bigint := 1314220021721;
seq_id bigint;
now_millis bigint;
shard_id int := 1;
BEGIN
SELECT nextval('global_id_seq')%1024 INTO seq_id;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - our_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