Created
January 11, 2025 03:32
-
-
Save fabiolimace/1e1db35eaeff529e1d94b22362d11d86 to your computer and use it in GitHub Desktop.
Pure SQL Function for Generating UUIDv7 on PostgreSQL
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 uuid7_sql() RETURNS uuid AS $$ | |
SELECT (FORMAT('%s-%s-%0s-%s-%s', | |
lpad(to_hex(trunc(EXTRACT(EPOCH FROM statement_timestamp()) * 1000)::bigint >> 16), 8, '0'), | |
lpad(to_hex(trunc(EXTRACT(EPOCH FROM statement_timestamp()) * 1000)::bigint & 65535), 4, '0'), | |
lpad(to_hex((trunc(random() * 2^12) + 28672)::bigint), 4, '0'), -- 28672 = 0x7000 | |
lpad(to_hex((trunc(random() * 2^14) + 32768)::bigint), 4, '0'), -- 32768 = 0x8000 | |
lpad(to_hex(trunc(random() * 2^48)::bigint), 12, '0')))::uuid; | |
$$ LANGUAGE SQL; | |
select uuid7_sql() -- 019450fe-7b0f-7ccc-8564-ad3ccc8234e0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another script to check function, and this script results the same as in previous script: