Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Last active May 27, 2025 19:46
Show Gist options
  • Save DarkGhostHunter/6fe782312b8b5cb37c3d3f6165697d39 to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/6fe782312b8b5cb37c3d3f6165697d39 to your computer and use it in GitHub Desktop.
Adds MIN/MAX UUID compatibility to PostgreSQL
-- Create a function to compare MAX uuid
CREATE OR REPLACE FUNCTION uuid_max(uuid, uuid)
RETURNS uuid AS $$
BEGIN
RETURN GREATEST($1, $2);
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
-- Create a function to compare MIN uuid
CREATE OR REPLACE FUNCTION uuid_min(uuid, uuid)
RETURNS uuid AS $$
BEGIN
RETURN LEAST($1, $2);
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
-- Create optimized binary MAX aggregate
CREATE OR REPLACE AGGREGATE max(uuid) (
SFUNC = uuid_max,
STYPE = uuid,
COMBINEFUNC = uuid_max,
PARALLEL = SAFE,
SORTOP = operator (>) -- Essential for index optimization
);
-- Create optimized binary MIN aggregate
CREATE OR REPLACE AGGREGATE min(uuid) (
SFUNC = uuid_min,
STYPE = uuid,
COMBINEFUNC = uuid_min,
PARALLEL = SAFE,
SORTOP = operator (<) -- Essential for index optimization
);
-- Delete the aggregators first, as they depend on the functions
DROP AGGREGATE IF EXISTS max(uuid);
DROP AGGREGATE IF EXISTS min(uuid);
-- Delete the functions since the aggregators are now gone
DROP AGGREGATE IF EXISTS uuid_max(uuid, uuid);
DROP AGGREGATE IF EXISTS uuid_min(uuid, uuid);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment