Thread: Absolute value on int2 or int4 field

Absolute value on int2 or int4 field

From
Chris Johnson
Date:
I need to sort a list of entries by the absolute value of a particular
field.  I examined the documentation and found that @ is the operator that
I need, but it doesn't appear to work on int2 or int4 fields.

Anyone have any ideas on how to accomplish this?

cmj=> create table test (a int2, b int4, c float4, d float8);
CREATE
cmj=> insert into test values (1,1,1,1);
INSERT 246399 1
cmj=> insert into test values (-2,-2,-2,-2);
INSERT 246400 1
cmj=> select * from test order by @a;
ERROR:  parser: parse error at or near "@"
cmj=> select * from test order by @b;
ERROR:  parser: parse error at or near "@"
cmj=> select @a from test;
ERROR:  Can't find left op: @ for type 21
cmj=> select @b from test;
ERROR:  Can't find left op: @ for type 23
cmj=> select @c from test;
?column?
--------
       1
       2
(2 rows)

cmj=> select @d from test;
?column?
--------
       1
       2
(2 rows)


If you've got an idea please feel free to enlighten me!

Chris

PS I'm tempted to just convert the fields to floating point, but that
   seems to easy.  ;-)


Re: [SQL] Absolute value on int2 or int4 field

From
Guido Piazzi
Date:
On Thu, 27 Aug 1998, Chris Johnson wrote:

> I need to sort a list of entries by the absolute value of a particular
> field.  I examined the documentation and found that @ is the operator that
> I need, but it doesn't appear to work on int2 or int4 fields.
>
> Anyone have any ideas on how to accomplish this?

guido=> select @a::float as abs from test order by abs;
abs
---
  1
  2
(2 rows)

I run 6.3.1 on Linux 2.0.27.  BTW, trying to insert -2 into float
fields without casting didn't work on my box!

Regards, Guido
--------------------------------------------
Guido Carlo Piazzi           gpiazzi@nemo.it
Non coronabitur nisi qui legitime certaverit