Skip site navigation (1) Skip section navigation (2)

Re: ORDER BY using specifc values

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Ian McWilton <ian(at)blazingcactus(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: ORDER BY using specifc values
Date: 2000-04-13 07:03:20
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-sql
Ian McWilton <ian(at)blazingcactus(dot)com> writes:
> I need to return the results of a SELECT ordered by a 
> column but in a way that is neither ascending or 
> descending. 

> The ORDER BY column can have one of five values and I 
> want to specify which values are returned in the list 
> in which order.

> An example table below shows the data in the DB:

> 1, A
> 2, B
> 3, B
> 4, C
> 5, B

> ...and what I want is for my queries result to be 
> ordered by VALUE with C put first in the list, then A, 
> then B.

> Having investigated it appears that ORDER BY does not 
> seem to be any help as it restricts the ordering to ASC 
> or DESC.

Make a function f(x) that converts the stored values into a suitable
ordering, say C -> 1, A -> 2, B -> 3.  Then do
	ORDER BY f(column)

If you have no more-elegant ideas at hand, f() could be defined
using a CASE expression.  In fact you could just write the CASE
expression right in ORDER BY, but if you need the same ordering
in many different queries then defining a function is probably
the way to go.

			regards, tom lane

In response to

pgsql-sql by date

Next:From: Oliver MueschkeDate: 2000-04-13 07:42:30
Subject: Re: ORDER BY using specifc values
Previous:From: Gerhard DieringerDate: 2000-04-13 06:32:59
Subject: Antw: ORDER BY using specifc values

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group