Working with Geospatial Data in SQL

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


If you’ve ever worked with large datasets, you know that they often contain geospatial data: information about the geographical location of the data points. SQL, with its powerful geospatial capabilities, allows you to not only store and retrieve this type of data but also perform complex queries and analysis.

Geospatial Date Types in SQL

SQL offers two main types of geospatial data types: geometry and geography. The geometry type is used for flat 2D spaces, while the geography type is optimized for spherical surfaces – like the Earth.

Creating a Table with Geospatial Data

Before we proceed, you need to understand how to create a table with geospatial data. Below is an example of SQL code:

In this case, we create a table called ‘Places’, where ‘Location’ uses the GEOGRAPHY data type.

Inserting Geospatial Data

You can insert geospatial data into the table with the use of the geography::STPointFromText method. Here’s an example:

This inserts a new row into the Places table, for ‘The Eiffel Tower’ with its corresponding latitude and longitude.

Querying Geospatial Data

You can run queries that calculate distances between two points. For instance, the following SQL command determines the distance (in meters) between two places:

This query calculates the geo-spatial distance between ‘Place1’ and ‘Place2’ in the dataset.

Summing Up

As you can see, SQL provides numerous tools for handling geospatial data. Understanding how to manipulate and analyze this data using SQL can open up many new opportunities for your data analytics projects.

Leave a Comment