Re: Natural ordering in postgresql? Does it exist?

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Clark Endrizzi <clarkendrizzi(at)hotmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Natural ordering in postgresql? Does it exist?
Date: 2004-12-11 01:38:33
Message-ID: 20041211013833.GA62296@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, Dec 10, 2004 at 02:47:53PM -0700, Clark Endrizzi wrote:

> I have a field that I'll be ordering and I noticed that ordering is done
> logically and would confuse my users here (1,12,16,4,8, etc).

I think you mean that the ordering is done lexically and you want
it done numerically. If the fields are entirely numeric then storing
them using one of the numeric types (INTEGER, NUMERIC, DOUBLE
PRECISION, etc.) will result in numeric sort orders. If you have
all-numeric values in VARCHAR/TEXT fields, then you can cast them
to one of the numeric types in the ORDER BY clause:

SELECT ...
ORDER BY fieldname::INTEGER;

If the values are a mixture of text and numbers (e.g., ABC-1, ABC-12,
etc.) then you could use string functions to order different parts
of the field differently:

SELECT ...
ORDER BY SUBSTRING(fieldname, 1, 3),
SUBSTRING(fieldname, 5)::INTEGER;

SELECT ...
ORDER BY SUBSTRING(fieldname FROM '^(\\w+)'),
SUBSTRING(fieldname FROM '(\\d+)')::INTEGER;

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Browse pgsql-general by date

  From Date Subject
Next Message itamar 2004-12-11 02:07:26 relation "table" does not exist
Previous Message Paul Tillotson 2004-12-11 01:22:25 Re: No mailing list posts