UUIDv7 in PostgreSQL

And another UUID function. This one also generates UUIDv7, just like the the one in the previous post

, but this one is designed to work in PostgresSQL, instead of MySQL
SELECT CONCAT(
	OVERLAY(LPAD(TO_HEX(FLOOR(EXTRACT('EPOCH' FROM NOW()::TIMESTAMP(3)) * 1000)::BIGINT), 12, '0') PLACING '-' FROM 9 FOR 0),
	'-7',
	LPAD(TO_HEX(FLOOR(RANDOM() * 0x1000)::BIGINT), 3, '0'),
	'-',
	TO_HEX(0x8000 | FLOOR(RANDOM() * 0x4000)::BIGINT),
	'-',
	LPAD(TO_HEX(FLOOR(RANDOM() * 0x1000000000000)::BIGINT), 12, '0')
)::UUID AS uuidv7;

As before: either use this inline in your select statement, or convert it to a function.

Comments are disabled for this post