Re: Random sort with distinct - Mailing list pgsql-sql

From Tom Lane
Subject Re: Random sort with distinct
Date
Msg-id 5070.1286027570@sss.pgh.pa.us
Whole thread Raw
In response to Random sort with distinct  ("Ozer, Pam" <pozer@automotive.com>)
List pgsql-sql
"Ozer, Pam" <pozer@automotive.com> writes:
> Select Distinct VehicleMake, VehicleModel
> From VehicleYearMakeModelTrim
> Order by random()
> Limit 10;

> I don't want to bring back the random number I just want the sort order
> to be random. How can I sort randomly?  This query breaks because
> random() is not in the select.

Well, yeah: the implication of the ORDER BY is that a new random value
is to be computed for each row of VehicleYearMakeModelTrim.  After you
combine rows with DISTINCT it's not clear which of those values should
be used to sort a grouped row.

You need to put the DISTINCT and the ORDER BY in separate query levels,
like this:

select * from (Select Distinct VehicleMake, VehicleModel  From VehicleYearMakeModelTrim) ss
Order by random()
Limit 10;
        regards, tom lane


pgsql-sql by date:

Previous
From: Lee Hachadoorian
Date:
Subject: Re: Random sort with distinct
Next
From: Frank Bax
Date:
Subject: join returns too many results...