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

From Poul Møller Hansen
Subject Re: Finding nearest numeric value
Date
Msg-id 430389B1.9050900@pbnet.dk
Whole thread Raw
In response to Re: Finding nearest numeric value  (Sean Davis <sdavis2@mail.nih.gov>)
List pgsql-general
>>>To find the nearest value in number_column to some CONSTANT (where you
>>>replace constant with a number), try:
>>>
>>>select *,(number_column - CONSTANT)^2 as d from tablename order by d limit
>>>1;
>>>
>>>Does that do it for you?
>>>
>>>Sean
>>>
>>>
>>
>>It does ideed, not that I understood how, but I will find out.
>>Thank you very much.
>
>
> Just a word (or several) of explanation, then....
>
> To compute the distance between two points on a line, you can compute the
> absolute value of the difference (4-2 is the same distance as 2-4, while the
> latter is negative) or you can square the difference (just to make it
> positive).  You could use absolute value in the above query if you like--I
> don't know which is faster, but they will give the same result.
>
> As for the query structure, you can select calculations of columns as well
> as the columns themselves.  The "as d" part just gives the calculation a
> nice name to use in the rest of the query and in the resulting output.
>
> Sean
>

Thanks for the explanation, guess I was fast giving up understanding the
query as it is actually quite simple :)

Of course there are the performance issues as argued by others, but the
table do only contain around 800 rows, so this method is adequate.

Thank you all for the inputs.


Poul

pgsql-general by date:

Previous
From: "A. Kretschmer"
Date:
Subject: Re: postgres 8.x on debian
Next
From: Sven Willenberger
Date:
Subject: Re: PostgreSQL 8.0.3 limiting max_connections to 64 ?