Sitemap
DBSQL SME Engineering

Publication for content from the DBSQL SME group and the surrounding community on DBSQL best practices, new design patterns, creative solutions, and real world user stories all in one place.

Unlocking Geospatial Analysis with Databricks SQL

9 min readOct 2, 2025

--

Native Geography and Geometry types and expanded Spatial SQL Expressions in DBR 17.1+

Press enter or click to view image in full size

Author: Jared Champion

Geospatial analytics has become increasingly critical for modern data-driven organizations, from location intelligence and urban planning to supply chain optimization and environmental monitoring. With the release of Databricks Runtime (DBR) 17.1, Databricks has significantly enhanced its geospatial SQL capabilities, introducing native geospatial data types and optimized functions that make spatial analysis more powerful and accessible than ever before.

This post will explore the new geospatial features in DBR 17.1 that can significantly improve spatial analytics in Databricks.

Let’s get ready to unlock the full potential of geospatial analytics on the Databricks Platform!

What’s new in DBR 17.1 — Geospatial Data Types and Functions

DBR 17.1 introduces native support for geospatial data types and additional functions to work with these types.

GEOMETRY type

The GEOMETRY type represents a geometry object (point, linestring, or polygon, etc.) using a Euclidean coordinate reference system (X, Y) and an optional Z coordinate, as though the Earth were flat. The underlying coordinate reference is described by the SRID value of the GEOMETRY type. There are over 11K SRIDs supported for this type.

Example:

SELECT st_geomfromtext(‘POINT(1 2)’, 4326);

GEOGRAPHY type

The GEOGRAPHY type represents a geographic object (point, linestring, polygon, etc.) using a geographic coordinate system on the Earth's surface. The coordinates are expected to be valid longitude and latitude values. Note: Currently, only 4326 is supported for this type.

Example:

SELECT st_geogfromtext(‘POINT(1 2)’);

80+ SPATIAL Functions

A wide range of spatial functions have also been added — too many to dive into for this post! We will review a select few, but please check out the full list at the link above. These functions can assist in importing/exporting spatial data, editing and updating spatial types, understanding spatial relationships, and transforming spatial data.

Working with Geospatial types in DBSQL

In the following sections, we will dive into the Geospatial types in Databricks! To follow along, ensure you are using a cluster with DBR 17.1 or higher. A sample notebook with the code used in this section is available here.

Let’s start by creating some sample geospatial data! For our example, let's take a retail use case. We will create tables to represent:

  • Retail Stores (points)
  • Delivery Zones (polygons)
  • Routes (paths)
  • Customer locations (points)

Retail Stores


-- Create a table of retail store locations using the new POINT geometry type

CREATE OR REPLACE TABLE IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores') AS
SELECT
store_id,
store_name,
city,
state,
ST_Point(longitude, latitude, 4326) as location,
annual_revenue,
employee_count,
store_type
FROM VALUES
(1, 'Downtown Seattle', 'Seattle', 'WA', -122.3328, 47.6061, 2500000, 25, 'flagship'),
(2, 'Pike Place Market', 'Seattle', 'WA', -122.3417, 47.6089, 1800000, 18, 'standard'),
(3, 'SFO Union Square', 'San Francisco', 'CA', -122.4074, 37.7873, 3200000, 32, 'flagship'),
(4, 'Mission District', 'San Francisco', 'CA', -122.4194, 37.7599, 1600000, 16, 'standard'),
(5, 'Beverly Hills', 'Los Angeles', 'CA', -118.4000, 34.0736, 2800000, 28, 'flagship'),
(6, 'Santa Monica', 'Los Angeles', 'CA', -118.4912, 34.0195, 2100000, 21, 'standard'),
(7, 'Times Square', 'New York', 'NY', -73.9857, 40.7580, 4200000, 42, 'flagship'),
(8, 'Brooklyn Heights', 'New York', 'NY', -73.9958, 40.6955, 1900000, 19, 'standard'),
(9, 'Michigan Avenue', 'Chicago', 'IL', -87.6244, 41.8781, 3100000, 31, 'flagship'),
(10, 'Lincoln Park', 'Chicago', 'IL', -87.6376, 41.9217, 1700000, 17, 'standard')
AS t(store_id, store_name, city, state, longitude, latitude, annual_revenue, employee_count, store_type);

We can see that this table has saved our location in the new geometry type!

-- Verify the store data and examine the geometry type
SELECT
store_name,
city,
location,
ST_AsText(location) as location_wkt,
ST_X(location) as longitude,
ST_Y(location) as latitude
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores')
LIMIT 5;

Delivery Zones


-- Create delivery zone polygons using ST_GeomFromText
CREATE OR REPLACE TABLE IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones') AS
SELECT
zone_id,
zone_name,
city,
ST_GeomFromText(zone_polygon, 4326) as zone_boundary,
max_delivery_time_minutes,
delivery_fee
FROM VALUES
(1, 'Seattle Central', 'Seattle', 'POLYGON((-122.3500 47.5900, -122.3200 47.5900, -122.3200 47.6200, -122.3500 47.6200, -122.3500 47.5900))', 30, 5.99),
(2, 'SF Downtown', 'San Francisco', 'POLYGON((-122.4200 37.7700, -122.3900 37.7700, -122.3900 37.8000, -122.4200 37.8000, -122.4200 37.7700))', 25, 7.99),
(3, 'LA West Side', 'Los Angeles', 'POLYGON((-118.5000 34.0000, -118.3500 34.0000, -118.3500 34.1000, -118.5000 34.1000, -118.5000 34.0000))', 45, 6.99),
(4, 'Manhattan Midtown', 'New York', 'POLYGON((-74.0000 40.7400, -73.9700 40.7400, -73.9700 40.7800, -74.0000 40.7800, -74.0000 40.7400))', 20, 8.99),
(5, 'Chicago Loop', 'Chicago', 'POLYGON((-87.6400 41.8600, -87.6100 41.8600, -87.6100 41.8900, -87.6400 41.8900, -87.6400 41.8600))', 35, 6.99)
AS t(zone_id, zone_name, city, zone_polygon, max_delivery_time_minutes, delivery_fee);

-- Examine the delivery zones
SELECT
zone_name,
city,
ST_AsText(zone_boundary) as polygon_wkt,
-- Use ST_Transform to change SRID to one that is measured in meters for easier calculation
ST_Area(ST_Transform(zone_boundary, 5070)) as area_sq_meters
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones');

Customer Data with H3 Integration

-- Create customer locations with H3 indexing (combining new geometry types with H3)
CREATE OR REPLACE TABLE IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') AS
SELECT
customer_id,
customer_name,
ST_Point(longitude, latitude, 4326) as location,
h3_pointash3(ST_AsText(location), 7) as h3_cell_level7,
city,
state,
last_order_date,
total_lifetime_value
FROM VALUES
(1001, 'Alice Johnson', -122.3350, 47.6062, 'Seattle', 'WA', '2025-01-15', 1250.00),
(1002, 'Bob Smith', -122.3400, 47.6080, 'Seattle', 'WA', '2025-01-20', 890.50),
(1003, 'Carol Davis', -122.4080, 37.7875, 'San Francisco', 'CA', '2025-01-18', 2100.75),
(1004, 'David Wilson', -122.4200, 37.7600, 'San Francisco', 'CA', '2025-01-22', 1650.25),
(1005, 'Eva Brown', -118.4010, 34.0740, 'Los Angeles', 'CA', '2025-01-17', 1890.00),
(1006, 'Frank Miller', -118.4920, 34.0200, 'Los Angeles', 'CA', '2025-01-25', 980.30),
(1007, 'Grace Lee', -73.9860, 40.7585, 'New York', 'NY', '2025-01-19', 2850.90),
(1008, 'Henry Garcia', -73.9960, 40.6960, 'New York', 'NY', '2025-01-21', 1320.60),
(1009, 'Iris Martinez', -87.6250, 41.8785, 'Chicago', 'IL', '2025-01-16', 1450.80),
(1010, 'Jack Rodriguez', -87.6380, 41.9220, 'Chicago', 'IL', '2025-01-23', 1750.40)
AS t(customer_id, customer_name, longitude, latitude, city, state, last_order_date, total_lifetime_value);
-- Verify customer data with H3 cells
SELECT
customer_name,
city,
ST_AsText(location) as point_wkt,
h3_cell_level7
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers')
LIMIT 5;

Examples of Geospatial Analytics on Retail Samples

Spatial Relationships and filtering

Get Databricks SQL SME’s stories in your inbox

Join Medium for free to get updates from this writer.

In this section, we are finding all customers within the delivery zones. We can use ST_DistanceSpheroid on SRID 4326 points to determine the distance in meters between two points on the Earth. As a performance trade-off, ST_DistanceSphere can be used instead at the cost of some accuracy.

-- Find all customers within delivery zones using ST_Within
SELECT
c.customer_name,
c.city,
dz.zone_name,
dz.delivery_fee,
-- ST_DistanceSperoid will give us meters to the zone centre
ST_DistanceSpheroid(c.location, ST_Centroid(dz.zone_boundary)) as distance_to_zone_center
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') c
JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones') dz ON dz.city = c.city
WHERE ST_Within(c.location, dz.zone_boundary)
ORDER BY c.city, distance_to_zone_center;
Press enter or click to view image in full size

Distance and Area calculations

Here, we are using a different method to obtain our measurement in meters. By leveraging the ST_Transform function to project our SRID 4326 coordinates to SRID 507,0, which is measured in meters.

Because we are using SRID 5070 here, we can leverage ST_Distance to directly calculate the distance in the native units (meters) instead of calling ST_DistanceSphere or ST_DistanceSpheroid. For more information on the differences between the distance functions, refer to the official launch post for Spatial SQL.


-- Calculate area of delivery zones and find nearest store
SELECT
dz.zone_name,
dz.city,
ROUND(ST_Area(ST_Transform(dz.zone_boundary, 5070)), 2) as area_sq_meters,
rs.store_name as nearest_store,
-- We can also project to the SRID that is measured in meters
ROUND(ST_Distance(ST_Centroid(ST_Transform(dz.zone_boundary, 5070)), ST_Transform(rs.location, 5070)), 2) as distance_to_store_meters
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones') dz
CROSS JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores') rs
WHERE rs.city = dz.city
QUALIFY ROW_NUMBER() OVER (PARTITION BY dz.zone_id ORDER BY ST_Distance(ST_Centroid(dz.zone_boundary), rs.location)) = 1
ORDER BY dz.city;

Buffer analysis for market expansion

-- Create 5km buffer zones around flagship stores to identify market opportunities
WITH flagship_buffers AS (
SELECT
store_id,
store_name,
city,
location,
ST_Buffer(location, 0.045) as buffer_5km -- Approximately 5km at these latitudes
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores')
WHERE store_type = 'flagship'
),
potential_customers AS (
SELECT
fb.store_name,
fb.city,
COUNT(c.customer_id) as customers_in_buffer,
ROUND(SUM(c.total_lifetime_value), 2) as total_market_value,
ROUND(AVG(c.total_lifetime_value), 2) as avg_customer_value
FROM flagship_buffers fb
LEFT JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') c ON ST_Within(c.location, fb.buffer_5km)
GROUP BY fb.store_id, fb.store_name, fb.city
)
SELECT * FROM potential_customers
ORDER BY total_market_value DESC;
Press enter or click to view image in full size

Density Analysis w/ H3 Aggregations

Let's use our sample dataset to visualise the density of our delivery zones. By finding all customers within a given hex boundary, we can see where our customers are clustered and where to focus our services.

-- Analyze customer density using H3 hexagonal grid
SELECT
h3_cell_level7,
h3_boundaryaswkt(h3_cell_level7) as hex_boundary,
COUNT(customer_id) as customer_count,
ROUND(SUM(total_lifetime_value), 2) as total_value,
ROUND(AVG(total_lifetime_value), 2) as avg_value_per_customer
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers')
GROUP BY h3_cell_level7
HAVING customer_count >= 1
ORDER BY total_value DESC;
Press enter or click to view image in full size

Performance with Spatial Data

Especially in these early days of the features, passing hints into the queries can significantly speed up our geospatial processing. If, for example, we know that one side of our join is small enough to fit in memory, then leveraging the existing broadcast hints can provide big boosts in performance!

-- Optimized: Broadcast the smaller delivery_zones table
SELECT /*+ BROADCAST(dz) */
c.customer_name,
dz.zone_name,
ROUND(ST_DistanceSpheroid(c.location, ST_Centroid(dz.zone_boundary)), 2) as distance_meters
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') c
JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones') dz ON ST_Within(c.location, dz.zone_boundary);

Delta Lake optimisations

Let's optimize the current tables and then run a complex query on the data.

-- Optimize tables for better query performance
ALTER TABLE customers_indexed CLUSTER BY (h3_level8);

-- Add table properties for better performance
ALTER TABLE customers_indexed SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);

Store Delivery Optimisation in Retail

-- Find optimal delivery dispatch
WITH customer_store_distances AS (
SELECT
c.customer_id,
c.customer_name,
c.location as customer_location,
rs.store_id,
rs.store_name,
rs.location as store_location,
ST_DistanceSpheroid(c.location, rs.location) as distance,
ROW_NUMBER() OVER (PARTITION BY c.customer_id ORDER BY ST_DistanceSpheroid(c.location, rs.location)) as store_rank
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') c
CROSS JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores') rs
WHERE rs.city = c.city -- Only consider stores in the same city
),
optimal_routes AS (
SELECT
customer_id,
customer_name,
store_id,
store_name,
distance as distance_meters
FROM customer_store_distances
WHERE store_rank = 1 -- Closest store
)
SELECT
store_name,
COUNT(customer_id) as assigned_customers,
ROUND(AVG(distance_meters), 2) as avg_distance_meters,
ROUND(SUM(distance_meters), 2) as total_route_distance
FROM optimal_routes
GROUP BY store_id, store_name
ORDER BY assigned_customers DESC;

Best Practices Summary

  • Leverage native geometry and geography types for type safety and performance
  • Broadcast small tables on large spatial joins (for now)
  • Combine ST functions and H3 approximations to efficiently operate on spatial data at scale
  • Leverage Databricks' in-built optimisations, such as liquid clustering

Finally, let's finish up with a comprehensive analysis of the Retail Supply chain coverage in our sample data:

-- Combine all components to determine where to most effectively invest to improve our service
WITH delivery_metrics AS (
SELECT
rs.store_id,
rs.store_name,
rs.city,
COUNT(DISTINCT c.customer_id) as total_customers,
ROUND(AVG(ST_DistanceSpheroid(rs.location, c.location)), 2) as avg_delivery_distance,
ROUND(SUM(c.total_lifetime_value), 2) as total_market_value,
-- Calculate service area using envelope around customers
ST_Envelope(ST_Union_Agg(c.location)) as service_area
FROM IDENTIFIER(:catalog || '.' || :schema || '.' || 'retail_stores') rs
LEFT JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'customers') c ON c.city = rs.city
GROUP BY rs.store_id, rs.store_name, rs.city
),
zone_coverage AS (
SELECT
dm.*,
dz.zone_name,
dz.max_delivery_time_minutes,
ROUND(
COALESCE(
ST_Area(ST_Intersection(dm.service_area, dz.zone_boundary)) /
NULLIF(ST_Area(dz.zone_boundary), 0),
0
), 3
) as zone_coverage_ratio
FROM delivery_metrics dm
LEFT JOIN IDENTIFIER(:catalog || '.' || :schema || '.' || 'delivery_zones') dz ON dz.city = dm.city
),
efficiency_metrics AS (
SELECT
*,
ROUND(total_market_value / NULLIF(avg_delivery_distance, 0), 2) as value_per_km,
CASE
WHEN zone_coverage_ratio > 0.8 THEN 'excellent'
WHEN zone_coverage_ratio > 0.6 THEN 'good'
WHEN zone_coverage_ratio > 0.3 THEN 'fair'
WHEN zone_coverage_ratio > 0.15 THEN 'partial'
ELSE 'needs_improvement'
END as coverage_rating
FROM zone_coverage
)
SELECT
store_name,
city,
total_customers,
avg_delivery_distance as avg_delivery_distance_m,
total_market_value,
value_per_km as efficiency_ratio,
ROUND(zone_coverage_ratio * 100, 1) as coverage_percentage,
coverage_rating
FROM efficiency_metrics
ORDER BY efficiency_ratio DESC;
Press enter or click to view image in full size

Conclusion

Hopefully, this has got you excited to start leveraging Spatial SQL for your Geospatial workloads on Databricks!

For further reading, take a look at the launch post for Spatial SQL. You can find all the code used in this post in the accompanying notebook here. Additional sample code and notebooks are also available in the Databricks Documentation.

--

--

Databricks SQL SME
Databricks SQL SME

One stop shop for all technical how-tos, demos, and best practices for building on Databricks SQL

DBSQL SME Engineering
DBSQL SME Engineering

Publication for content from the DBSQL SME group and the surrounding community on DBSQL best practices, new design patterns, creative solutions, and real world user stories all in one place.