Skip to content

Instantly share code, notes, and snippets.

@craigs
Last active October 20, 2025 23:44
Show Gist options
  • Select an option

  • Save craigs/02a3ea2e651d28553629287b78183e49 to your computer and use it in GitHub Desktop.

Select an option

Save craigs/02a3ea2e651d28553629287b78183e49 to your computer and use it in GitHub Desktop.
Postgres uuid_generate_v7 function
CREATE OR REPLACE FUNCTION uuid_generate_v7() RETURNS uuid AS $$
DECLARE
unix_ts_ms bytea;
uuid_bytes bytea;
BEGIN
unix_ts_ms = substring(int8send((extract(epoch from clock_timestamp()) * 1000)::bigint) from 3);
uuid_bytes = uuid_send(gen_random_uuid());
uuid_bytes = overlay(uuid_bytes placing unix_ts_ms from 1 for 6);
uuid_bytes = set_bit(set_bit(uuid_bytes, 53, 1), 52, 1);
RETURN encode(uuid_bytes, 'hex')::uuid;
END
$$ LANGUAGE plpgsql VOLATILE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment