SQL
Geolocation
Latitude and Longitude
Database Queries
Spatial Data Analysis

Find nearest latitude/longitude with an SQL query

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Finding the nearest latitude and longitude in SQL usually means calculating distance from a target point to every stored point, then ordering by that distance. The best exact approach depends on your database, but the general strategy is the same whether you use plain SQL math or a spatial extension such as PostGIS.

The Basic Distance Problem

Latitude and longitude are coordinates on a sphere-like surface, not flat x and y values. That means simple Euclidean distance on raw degrees is only an approximation and becomes less accurate over larger areas.

For many databases without full GIS support, the usual fallback is the Haversine formula or a closely related spherical-distance formula.

Plain SQL With Great-Circle Distance

Suppose you have a table called locations:

sql
1CREATE TABLE locations (
2    id BIGINT PRIMARY KEY,
3    name VARCHAR(100),
4    latitude DOUBLE PRECISION,
5    longitude DOUBLE PRECISION
6);

To find the nearest row to a target latitude and longitude, you can compute the distance inline:

sql
1SELECT
2    id,
3    name,
4    latitude,
5    longitude,
6    6371 * ACOS(
7        COS(RADIANS(:target_lat)) *
8        COS(RADIANS(latitude)) *
9        COS(RADIANS(longitude) - RADIANS(:target_lng)) +
10        SIN(RADIANS(:target_lat)) *
11        SIN(RADIANS(latitude))
12    ) AS distance_km
13FROM locations
14ORDER BY distance_km
15LIMIT 1;

Here 6371 is the approximate Earth radius in kilometers. If you want miles, use about 3959 instead.

This works well for moderate datasets, but it forces the database to compute a distance for many rows unless you reduce the search area first.

Speeding It Up With a Bounding Box

A common optimization is to filter to a rough latitude and longitude window before running the exact distance formula:

sql
1SELECT
2    id,
3    name,
4    latitude,
5    longitude,
6    6371 * ACOS(
7        COS(RADIANS(:target_lat)) *
8        COS(RADIANS(latitude)) *
9        COS(RADIANS(longitude) - RADIANS(:target_lng)) +
10        SIN(RADIANS(:target_lat)) *
11        SIN(RADIANS(latitude))
12    ) AS distance_km
13FROM locations
14WHERE latitude BETWEEN :target_lat - 1 AND :target_lat + 1
15  AND longitude BETWEEN :target_lng - 1 AND :target_lng + 1
16ORDER BY distance_km
17LIMIT 10;

The bounding box is an approximation, but it can shrink the candidate set dramatically. After that, the exact formula orders only the nearby rows.

Spatial Databases Are Better When Available

If your database supports geographic types and spatial indexes, use them. In PostGIS, for example, the query becomes both cleaner and faster:

sql
1SELECT
2    id,
3    name,
4    ST_DistanceSphere(
5        geom,
6        ST_MakePoint(:target_lng, :target_lat)
7    ) AS distance_meters
8FROM places
9ORDER BY geom <-> ST_MakePoint(:target_lng, :target_lat)
10LIMIT 1;

With a proper spatial index, the database can narrow the search efficiently instead of calculating spherical distance for every row in the table.

Schema Design Matters

If nearest-neighbor lookups are important to the application, store the data in a way the database can index effectively. Plain numeric latitude and longitude columns can work, but spatial column types are usually a better long-term design for location-heavy systems.

This matters even more when the dataset grows beyond a few thousand rows. A query that feels instant on a development laptop can become expensive in production if every search scans the whole table.

Common Pitfalls

The biggest mistake is treating latitude and longitude as flat coordinates and using plain Pythagorean distance everywhere. That can be noticeably wrong over larger geographic areas.

Another issue is forgetting that longitude and latitude are ordered differently in some GIS functions. Many APIs expect longitude first and latitude second.

Teams also jump straight to the distance formula without any indexing or bounding-box strategy. That works for tiny tables and then slows down badly as the dataset grows.

Summary

  • The general solution is to compute distance from the target point and order by the smallest result.
  • Without GIS support, use a spherical-distance formula such as Haversine or an equivalent trigonometric expression.
  • Add a bounding-box filter to reduce the number of expensive distance calculations.
  • Prefer spatial types and indexes when the database supports them.
  • Be careful with coordinate order and with flat-Earth approximations that ignore spherical geometry.

Course illustration
Course illustration

All Rights Reserved.