Last active
October 20, 2025 23:44
-
-
Save craigs/02a3ea2e651d28553629287b78183e49 to your computer and use it in GitHub Desktop.
Postgres uuid_generate_v7 function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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