Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3873254
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T22:00:56+00:00 2026-05-19T22:00:56+00:00

Please forgive the awkward title. I had a hard time distilling my question into

  • 0

Please forgive the awkward title. I had a hard time distilling my question into one phrase. If anyone can come up with a better one, feel free.

I have the following simplified schema:

vendors
  INT id

locations
  INT id
  INT vendor_id
  FLOAT latitude
  FLOAT longitude

I am perfectly capable of return a list of the nearest vendors, sorted by proximity, limited by an approximation of radius:

SELECT * FROM locations
WHERE latitude IS NOT NULL AND longitude IS NOT NULL
  AND ABS(latitude - 30) + ABS(longitude - 30) < 50
ORDER BY ABS(latitude - 30) + ABS(longitude - 30) ASC

I can’t at this moment find my way around the repetition of the order/limit term. I initially attempted aliasing it as “distance” among the SELECT fields, but psql told me that this alias wasn’t available in the WHERE clause. Fine. If there’s some fancy pants way around this, I’m all ears, but on to my main question:

What I’d like to do is to return a list of vendors, each joined with the closest of its locations, and have this list ordered by proximity and limited by radius.

So supposing I have 2 vendors, each with two locations. I want a query that limits the radius such that only one of the four locations is within it to return that location’s associated vendor alongside the vendor itself. If the radius encompassed all the locations, I’d want vendor 1 presented with the closest between its locations and vendor 2 with the closest between its locations, ultimately ordering vendors 1 and 2 based on the proximity of their closest location.

In MySQL, I managed to get the closest location in each vendor’s row by using GROUP BY and then MIN(distance). But PostgreSQL seems to be stricter on the usage of GROUP BY.

I’d like to, if possible, avoid meddling with the SELECT clause. I’d also like to, if possible reuse the WHERE and ORDER parts of the above query. But these are by no means absolute requirements.

I have made hackneyed attempts at DISTINCT ON and GROUP BY, but these gave me a fair bit of trouble, mostly in terms of me missing mirrored statements elsewhere, which I won’t elaborate in great detail on now.


Solution

I ended up adopting a solution based off OMG Ponies’ excellent answer.

SELECT vendors.* FROM (
  SELECT locations.*, 
    ABS(locations.latitude - 2.1) + ABS(locations.longitude - 2.1) AS distance,
    ROW_NUMBER() OVER(PARTITION BY locations.locatable_id, locations.locatable_type
      ORDER BY ABS(locations.latitude - 2.1) + ABS(locations.longitude - 2.1) ASC) AS rank
    FROM locations
    WHERE locations.latitude IS NOT NULL
    AND locations.longitude IS NOT NULL
    AND locations.locatable_type = 'Vendor'
  ) ranked_locations
INNER JOIN vendors ON vendors.id = ranked_locations.locatable_id
WHERE (ranked_locations.rank = 1)
  AND (ranked_locations.distance <= 0.5)
ORDER BY ranked_locations.distance;

Some deviations from OMG Ponies’ solution:

  • Locations are now polymorphically associated via _type. A bit of a premise change.
  • I moved the join outside the subquery. I don’t know if there are performance implications, but it made sense in my mind to see the subquery as a getting of locations and partitioned rankings and then the larger query as an act of bringing it all together.
  • minor Took away table name aliasing. Although I’m plenty used to aliasing, it just made it harder for me to follow along. I’ll wait until I’m more experienced with PostgreSQL before working in that flair.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T22:00:57+00:00Added an answer on May 19, 2026 at 10:00 pm

    For PostgreSQL 8.4+, you can use analytics like ROW_NUMBER:

    SELECT x.*
      FROM (SELECT v.*,
                   t.*,
                   ABS(t.latitude - 30) + ABS(t.longitude - 30) AS distance,
                   ROW_NUMBER() OVER(PARTITION BY v.id
                                         ORDER BY ABS(t.latitude - 30) + ABS(t.longitude - 30)) AS rank
              FROM VENDORS v
              JOIN LOCATIONS t ON t.vendor_id = v.id
             WHERE t.latitude IS NOT NULL 
               AND t.longitude IS NOT NULL) x
      WHERE x.rank = 1
        AND x.distance < 50
    ORDER BY x.distance
    

    I left the filtering on distance, in case the top ranked value was over 50 so the vendor would not appear. Remove the distance check being less than 50 portion if you don’t want this to happen.

    ROW_NUMBER will return a distinct sequential value that resets for every vendor in this example. If you want duplicates, you’d need to look at using DENSE_RANK.

    See this article for emulating ROW_NUMBER on PostgreSQL pre-8.4.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please forgive the bad title - I had a hard time trying to think
Please forgive the clumsy question (if you can figure out a better way to
Please forgive the awkwardness of this question, I honestly don't know how to phrase
Please forgive the question if it is an obvious one, but I am new
Please forgive me if this is a dumb question. I'm only a week into
please forgive me for this idiot question. I understood that we can send push
Please forgive me if this is an obvious one. I have an unknown amount
Please forgive the simplicity of this question. The answer will be obvious to many
Veterans please forgive me for asking silly question. I understand that a class having
Please forgive the newb question, but I am not finding answers elsewhere... probably because

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.