Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created November 29, 2023 16:08
Show Gist options
  • Save benoittgt/299ab79adbb4e56f276cc935e73b6741 to your computer and use it in GitHub Desktop.
Save benoittgt/299ab79adbb4e56f276cc935e73b6741 to your computer and use it in GitHub Desktop.
max uuid
-- Create a table with a UUID column
CREATE TABLE your_table (
id serial PRIMARY KEY,
uuid_column uuid
);
-- Insert 400 rows with UUIDs
INSERT INTO your_table (uuid_column)
SELECT gen_random_uuid() FROM generate_series(1, 400);
SELECT max(uuid_column) from your_table;
/*
Same error as for pgslice
ERROR: function max(uuid) does not exist
LINE 1: SELECT max(uuid_column) from your_table;
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
*/
-- https://gist.github.com/devodo/8b39748d65e8185fbd89
CREATE OR REPLACE FUNCTION max (uuid, uuid)
RETURNS uuid AS $$
BEGIN
IF $1 IS NULL OR $1 < $2 THEN
RETURN $2;
END IF;
RETURN $1;
END;
$$ LANGUAGE plpgsql;
CREATE AGGREGATE max (uuid)
(
sfunc = max,
stype = uuid
);
SELECT max(uuid_column) from your_table;
-- No more issue
-- ffbfca39-7664-495a-b6fe-025ea1c7e6b1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment