Re: Finding nearest numeric value - Mailing list pgsql-general

From Richard Huxton
Subject Re: Finding nearest numeric value
Date
Msg-id 43035354.3040608@archonet.com
Whole thread Raw
In response to Finding nearest numeric value  (Poul Møller Hansen <freebsd@pbnet.dk>)
Responses Re: Finding nearest numeric value  (Csaba Nagy <nagy@ecircle-ag.com>)
Re: Finding nearest numeric value  (Ron Mayer <rm_pg@cheapcomplexdevices.com>)
Re: Finding nearest numeric value  (Peter Fein <pfein@pobox.com>)
List 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


pgsql-general by date:

Previous
From: "Jonathan Villa"
Date:
Subject: Re: Adding contrib modules
Next
From: Sean Davis
Date:
Subject: Re: Finding nearest numeric value