Geo Functions

Built-in functions for location-based queries and distance calculations

SemQL has two built-in geo functions for working with coordinates: GEO_DISTANCE() and GEO_WITHIN_RADIUS(). Both take latitude/longitude pairs and return results you can use directly in your queries.

These functions are database-agnostic — they work regardless of which database you're connected to (Snowflake, BigQuery, Redshift, etc.), because SemQL compiles them to standard trigonometry (the Haversine formula) that runs on any SQL engine.


GEO_DISTANCE

Returns the distance in kilometers between two geographic coordinates.

Syntax

GEO_DISTANCE(lat1, lng1, lat2, lng2)
Parameter
Type
Description

lat1

number

Latitude of the first point

lng1

number

Longitude of the first point

lat2

number

Latitude of the second point

lng2

number

Longitude of the second point

Examples

Distance from a fixed point to a column value:

SELECT
    store_name,
    city,
    GEO_DISTANCE(48.8566, 2.3522, store_lat, store_lng) AS distance_from_paris_km
FROM retail_stores
ORDER BY distance_from_paris_km ASC

Filter by a calculated distance:

Distance between two columns (e.g., customer location to nearest warehouse):


GEO_WITHIN_RADIUS

Returns true if a point is within a given radius of another point, false otherwise. Useful for filtering by proximity.

Syntax

Parameter
Type
Description

lat1

number

Latitude of the reference point

lng1

number

Longitude of the reference point

lat2

number

Latitude of the point to test

lng2

number

Longitude of the point to test

radius_km

number

Radius in kilometers

Examples

Filter stores within 25 km of a city:

Categorize records by proximity:

Count customers within a radius:


Combining both functions

A common pattern is to show the actual distance alongside a proximity flag:


Notes

  • Coordinates must be numeric (decimal degrees). Null coordinates will cause an error.

  • Distances are always in kilometers.

  • The Haversine formula assumes a spherical Earth — it's accurate to within ~0.5% for most practical distances.

  • Both functions are compiled to standard SQL math functions (SIN, COS, ACOS, RADIANS) and work on all supported database dialects.

Last updated