1

I am going through code for a legacy application backended by PostgreSQL (I think it was PG version 9.1).

I came across this function - which I guess is for custom aggregates, but do not understand what it is doing:

CREATE OR REPLACE FUNCTION _final_mode(anyarray)
  RETURNS anyelement AS
$BODY$
    SELECT a
    FROM unnest($1) a
    GROUP BY 1 
    ORDER BY COUNT(1) DESC, 1
    LIMIT 1;
$BODY$
LANGUAGE 'sql' IMMUTABLE;

-- Tell Postgres how to use our aggregate
CREATE AGGREGATE mode(anyelement) (
  SFUNC=array_append, --Function to call for each row. Just builds the array
  STYPE=anyarray,
  FINALFUNC=_final_mode, --Function to call after everything has been added to array
  INITCOND='{}' --Initialize an empty array when starting
);

Can anyone explain what the function is doing?

1 Answer 1

3

This aggregate function will return the element that occurs most often, breaking the tie by using the one that sorts first if there are more elements that occur equally often.

In a table atab like

 x
---
 a
 z
 q
 a
 b
 a
 z
 z

You will get the following:

SELECT mode(x) FROM atab;

 mode
------
    a
(1 row)

because both a and z occur three times, but a sorts before z lexically.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic explanation thanks. With the benefit of hindsight, the purpose of the function was indicated by the name ;) !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.