Question

Assuming a Postgres Table containing zip as varchar(10) I want to get either all results matching a specific zip or extend my results with entries close to the queried one in case there are not enough results. Say:

A user searches for zip "56500" and my result-set returns 2 items running an exact match. In this case I want to perform a kind of like query that finds "565%" entries. Eventually I need to run this in one query.

Any suggestions?

Was it helpful?

Solution

Something like this might be what you want:

SELECT …
FROM atable
WHERE zip = @zip

UNION ALL

SELECT …
FROM atable
WHERE NOT EXISTS (
  SELECT *
  FROM atable
  WHERE zip = @zip
)
  AND zip LIKE CONCAT(LEFT(@zip, 3), '%')

This may not be the most efficient solution, but at least it is a single query so might do well as a starting point.

OTHER TIPS

ORDER BY the delta from the desired zip?

So, this is not specifically for PostgreSQL -- it was actually written for MySQL originally -- but it should work. I came across this article a while back that showed how to create a database containing zipcodes and latitude/longitude for each zipcode, then using trigonometry to calculate the distance between zip codes. Take a look at the link. I'm sure it will help you...

http://www.chrissibert.com/blog/2009/06/16/mysql-zip-codes-latitude-longitude-distance/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top