Re: Finding nearest numeric value

From: Richard Huxton <dev(at)archonet(dot)com>
To: Poul Møller Hansen <freebsd(at)pbnet(dot)dk>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Finding nearest numeric value
Date: 2005-08-17 15:10:12
Message-ID: 43035354.3040608@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Poul Møller Hansen wrote:
> Does anyone know how to find the row with the nearest numeric value, not
> necessarily an exact match ?

While the other answers all do their job, and in one go too, I'd be
surprised if you found anything faster than:

SELECT myval FROM mytable WHERE myval > 1234 ORDER BY myval LIMIT 1
UNION ALL
SELECT myval FROM mytable WHERE myval < 1234 ORDER BY myval DESC LIMIT 1

That gives you (up to) two values to look at, but should use any index
you have on myval.

You can always sort the results by abs(myval) then if you don't want to
handle two values in the application layer.

--
Richard Huxton
Archonet Ltd

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Sean Davis 2005-08-17 15:21:31 Re: Finding nearest numeric value
Previous Message Tom Lane 2005-08-17 15:06:55 Re: Postgresql server "crash" after some day