Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created September 14, 2012 14:55
Show Gist options
  • Save sycobuny/3722411 to your computer and use it in GitHub Desktop.
Save sycobuny/3722411 to your computer and use it in GitHub Desktop.
Cheap non-aggregate MAX() and AVG() functions
CREATE OR REPLACE
FUNCTION MYAVG(VARIADIC NUMERIC[])
RETURNS NUMERIC
LANGUAGE SQL
AS 'SELECT AVG(unnest) FROM UNNEST($1)';
CREATE OR REPLACE
FUNCTION MYMAX(VARIADIC INTEGER[])
RETURNS INTEGER
LANGUAGE SQL
AS 'SELECT MAX(unnest) FROM UNNEST($1)';
@rintaun
Copy link

rintaun commented Sep 14, 2012

socialthing=# CREATE OR REPLACE
socialthing-# FUNCTION MAX(VARIADIC INTEGER[])
socialthing-# RETURNS INTEGER
socialthing-# LANGUAGE SQL
socialthing-# AS 'SELECT MAX(unnest) FROM UNNEST($1)';
CREATE FUNCTION
socialthing=# SELECT MAX(1,3,2);

max

3
(1 row)

socialthing=# SELECT max(popularity) FROM topic_results;

max

11248
(1 row)

@sycobuny
Copy link
Author

Sweet. Well, I suppose, absent any other evidence to the contrary, that it's not necessary to do MYAVG()/MYMAX() at all after all. That'd certainly make it syntactically prettier.

@sycobuny
Copy link
Author

That is, to name them MYcrap() instead of just crap(). I'd go back and edit my comment but I suppose that's not possible? Or I'm an idiot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment