Re: Finding nearest numeric value

From: Poul Møller Hansen <freebsd(at)pbnet(dot)dk>
To: Sean Davis <sdavis2(at)mail(dot)nih(dot)gov>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Finding nearest numeric value
Date: 2005-08-17 19:02:09
Message-ID: 430389B1.9050900@pbnet.dk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Sven Willenberger 2005-08-17 19:03:10 Re: PostgreSQL 8.0.3 limiting max_connections to 64 ?
Previous Message Peter Fein 2005-08-17 19:00:06 Re: Finding nearest numeric value