Re: How to search for a part of a number

From: Harald Fuchs <hari(dot)fuchs(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: How to search for a part of a number
Date: 2010-10-25 13:13:51
Message-ID: 86tykao1o0.fsf@mgm.protecting.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

In article <4CC4D3E2(dot)7090302(at)gmx(dot)net>,
Andreas <maps(dot)on(at)gmx(dot)net> writes:

> Hi,
> I'm wondering if there was a clever way to find parts of a numeric
> string in another table.
> There is a table that holds city-codes and city-names. City-code would
> be the part of a phone number that identifies the city.
> Over here this code can have 2 - 5 digits. So the table would contain:
> 23 ; A-City
> 345 ; B-Town
> 4455 ; C-Village
> 632 ; D-Town
> ...

> I'm quite sure the numbering system is bound to be spanning a search tree.

> So there are 2 tasks:
> a) I'd get 445598765 in and like to know the corresponding city

If the prefixes are unique:

SELECT code, name
FROM tbl
WHERE '445598765' LIKE code || '%'

If not:

SELECT code, name
FROM tbl
WHERE '445598765' LIKE code || '%'
ORDER BY length(code) DESC
LIMIT 1

If your table is so large that seqscans hurt you, use the 'prefix'
contrib package.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Axel Rau 2010-10-25 16:07:51 Using PL/pgSQL text argument in 'IN (INT,INT,...)' clause [re-post]
Previous Message Axel Rau 2010-10-25 10:14:22 Using PL/pgSQL text argument in 'IN (INT,INT,...)' clause