Aggregate Random

From PostgreSQL wiki

Revision as of 10:40, 25 April 2013 by Ppkrauss (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

A random value is obtained by the random() buildin function, but sometimes, you want a random element from a grouping.



Aggregate Random

Works with PostgreSQL

Any version

Written in


Depends on


This snippet allows you to use random() as an aggregate function. It is also part of the ulib_agg user-defined library.

It should distribute the choices uniformly over each row in the grouping, whether the value selected is NULL or not. (you could modify SFUNC if you wanted to have it select a random non-NULL element)

CREATE OR REPLACE FUNCTION _final_random(anyarray)           
 RETURNS anyelement AS
 SELECT $1[array_lower($1,1) + FLOOR((1 + array_upper($1, 1) - array_lower($1, 1))*random())];
CREATE AGGREGATE random(anyelement) (
  SFUNC=array_append, --Function to call for each row. Just builds the array
  FINALFUNC=_final_random, --Function to call after everything has been added to array
  INITCOND='{}' --Initialize an empty array when starting


SELECT random(x) AS array_of_randoms_from1_toX FROM t;
Personal tools