SQL Spatial Data Types

This document provides an overview of spatial data types in SQL Server, covering their purpose, usage, and key functionalities.

Introduction to Spatial Data

Spatial data types allow you to store and query geographic information, such as points, lines, polygons, and more, directly within your SQL Server database. This enables powerful location-based services, mapping applications, and spatial analysis.

SQL Server supports two main spatial data types:

The GEOMETRY Data Type

The GEOMETRY data type stores data in a Cartesian coordinate system. Common methods include:

Common GEOMETRY Objects

Example Usage (GEOMETRY)

Creating a simple point:


DECLARE @point GEOMETRY = GEOMETRY::STGeomFromText('POINT(1 1)', 0);
SELECT @point.STAsText();
                

Creating a polygon:


DECLARE @polygon GEOMETRY = GEOMETRY::STGeomFromText('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))', 0);
SELECT @polygon.STArea();
                

The GEOGRAPHY Data Type

The GEOGRAPHY data type uses a spherical model of the Earth, typically based on the SRID (Spatial Reference Identifier) for WGS 84 (SRID 4326). This ensures that spatial calculations are geographically accurate.

Common GEOGRAPHY Objects

Example Usage (GEOGRAPHY)

Creating a point with WGS 84 coordinates:


DECLARE @city GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT(-74.0060 40.7128)', 4326);
SELECT @city.STDistance(GEOGRAPHY::STGeomFromText('POINT(-118.2437 34.0522)', 4326)); -- Distance to Los Angeles
                

Checking if a point is within a country (simplified example):


DECLARE @usa GEOGRAPHY = GEOGRAPHY::STGeomFromText('POLYGON((-124.73 24.53, -66.95 24.53, -66.95 49.37, -124.73 49.37, -124.73 24.53))', 4326);
DECLARE @ny GEOGRAPHY = GEOGRAPHY::STGeomFromText('POINT(-74.0060 40.7128)', 4326);
SELECT @ny.STWithin(@usa); -- Returns 1 (true) if within the USA polygon
                

Spatial Indexes

To efficiently query large amounts of spatial data, it's crucial to create spatial indexes. SQL Server offers two types of spatial indexes:

Creating a spatial index significantly improves the performance of operations that involve spatial relationships.

Further Reading