From: Terry Fielder <terry@ashtonwoodshomes.com>
To: Bryce W Nesbitt <bryce1@obviously.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: casting character varying to integer - order by numeric
Date: Wed, 19 Oct 2005 21:34:17 -0400
Message-ID: <4356F419.3010105@ashtonwoodshomes.com> (raw)
In-Reply-To: <4356EC5D.4080706@obviously.com>
References: <4356EC5D.4080706@obviously.com>
Check out the function to_number()
In particular here's an example...
If a field named section is text containing numbers:
ORDER BY to_number(t.section, text(99999999))
If the field can also contain non-numerals such as 3a, 3b, and you want
3a to show first then do this:
ORDER BY to_number(t.section, text(99999999)), t.section
And if the field section can actually START with an alpha, then to
prevent to_number from failing do this:
to_number(textcat('0', t.section), text(99999999)), t.section
Terry
Bryce W Nesbitt wrote:
> How can I force a character field to sort as a numeric field?
> I've got something like this:
>
> Postgres=> SELECT username,last_name
> FROM eg_member ORDER BY username;
> ----------+-----------
> 0120 | Foley
> 1 | Sullivan
> 10 | Guest
> 11 | User
> (5 rows)
>
> (I can't change the field type). I tried:
>
> SELECT username,last_name
> FROM eg_member ORDER BY username::integer;
>
> But postgres 7 rejects this with "ERROR: cannot cast type character
> varying to integer". Is there a way to force numeric sort order? I
> tried a variety of functions, such as to_char() and convert() without
> any luck. Thanks for your insight!
>
>
> ---------------------------(end of broadcast)---------------------------
> TIP 2: Don't 'kill -9' the postmaster
>
--
Terry Fielder
terry@greatgulfhomes.com
Associate Director Software Development and Deployment
Great Gulf Homes / Ashton Woods Homes
Fax: (416) 441-9085
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: terry@ashtonwoodshomes.com, bryce1@obviously.com
Subject: Re: casting character varying to integer - order by numeric
In-Reply-To: <4356F419.3010105@ashtonwoodshomes.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox