w3resource

Locate Nearby Points Based on Proximity


Find Locations Within a Radius

Write a MySQL query to retrieve all locations within a specified radius (e.g., 1000 units) from a given point.

Solution:

-- Select locations from the Locations table that are within a 1000-unit radius of a given reference point.
SELECT name

-- Retrieve data from the Locations table.
FROM Locations

-- Filter the results to include only those locations where the distance between the 'location' column 
-- and the reference point (created using ST_GeomFromText) is less than or equal to 1000 units.
WHERE ST_Distance(location, ST_GeomFromText('POINT(-73.985130 40.758896)')) <= 1000;

Explanation:

  • Purpose of the Query:
    • The goal is to filter locations based on proximity to a specified point.
    • This demonstrates using a spatial function to perform radius-based searches.
  • Key Components:
    • ST_Distance(...) <= 1000 : Filters records where the computed distance is within 1000 units.
  • Real-World Application:
    • Commonly used in location-based services to find nearby facilities.

Notes:

  • Adjust the radius based on the coordinate system and real-world distances.

For more Practice: Solve these Related Problems:

  • Write a MySQL query to select records from "GeoLocations" where the distance from a specified point is less than a given radius using ST_Distance.
  • Write a MySQL query to retrieve all locations in "Locations" that lie within 500 meters of a provided coordinate.
  • Write a MySQL query to find all "Shops" records where the spatial distance to a reference point is within 1000 units.
  • Write a MySQL query to fetch entries from "Parks" that are located inside a circular area defined by a center point and a specified radius.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous MySQL Exercise: Calculate Distance between Two Points.
Next MySQL Exercise: Check if a Point is Within a Polygon.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.