Skip to content

Instantly share code, notes, and snippets.

@j4k
Created October 24, 2013 09:08
Show Gist options
  • Save j4k/7133787 to your computer and use it in GitHub Desktop.
Save j4k/7133787 to your computer and use it in GitHub Desktop.
PostgreSQL fast distance query
WITH in_radius AS (
SELECT id
FROM table
WHERE earth_box( ll_to_earth( 51.534901, -0.204573), 5000.00) @> ll_to_earth(table.lat, table.lng)
), results AS (
SELECT *
FROM spaces
WHERE id IN (SELECT id FROM in_radius)
)
SELECT *,
earth_distance(ll_to_earth( 51.534901, -0.204573 ), ll_to_earth(results.lat, results.lng)) as distance
FROM results
INNER JOIN users on results.user_id = users.id
WHERE results.show = 1
ORDER BY distance ASC;
// index the tables lat lng float8's for better speed
CREATE INDEX ${name_of_index} on table USING gist(ll_to_earth(lat, lng));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment