Spatial SQL Cheat Sheet

Spatial SQL Cheat Sheet

There is a drawer in my desk that has been in the same place for twenty years, and in it lies a single, much-folded sheet of paper. It is a list of sql/” data-khs-tag=”147″>spatial SQL functions, with scribbled examples in three different colors of ink. Whenever a colleague asks me how to find the nearest hospital to every school, or count points in polygons, or repair a broken geometry, I do not reach for a manual. I reach for that drawer. A good cheat sheet is not a substitute for understanding. It is a memory aid for the things you understand but cannot recall at 4:55 on a Friday.

This article is that sheet, written out properly. It focuses on PostGIS, the spatial extension of PostgreSQL, because it is the most widely used spatial SQL environment and the one with the richest function library. Most of the ideas transfer to SpatiaLite, GeoPackage’s SQL interface, DuckDB, BigQuery and other systems, with small differences that I’ll point out at the end.

You don’t need to read it in order. Skim the headings, find the pattern you need and copy it. If spatial databases are new to you, begin with PostGIS: A Practical Introduction, and for the architecture around them, Enterprise GIS & Spatial Databases: PostGIS, Geodatabases, and Server Architecture.

Diagram: Most spatial SQL queries combine functions that measure, relate, build or transform geometries.
Most spatial SQL queries combine functions that measure, relate, build or transform geometries.

SQL in Sixty Seconds

If you’ve never written SQL, this is the whole skeleton of a query.

SELECT   d.name, COUNT(*) AS n_schools        -- what you want back
FROM     districts d                          -- from which table
JOIN     schools s ON s.district_id = d.id    -- combined with another table
WHERE    d.population > 10000                 -- keep only matching rows
GROUP BY d.name                               -- summarize per group
HAVING   COUNT(*) > 5                         -- filter the groups
ORDER BY n_schools DESC                       -- sort
LIMIT    10;                                  -- only the first rows

Three other tools you’ll use constantly:

-- A common table expression (CTE): a named step in a longer query
WITH big_districts AS (
  SELECT id, name, geom FROM districts WHERE population > 50000
)
SELECT name FROM big_districts;

-- CASE: conditional values
SELECT name, CASE WHEN population > 50000 THEN 'large' ELSE 'small' END AS size_class FROM districts;

-- A window function: ranking without collapsing the rows
SELECT name, population, ROW_NUMBER() OVER (ORDER BY population DESC) AS rank FROM districts;

Everything below plugs into this skeleton.


Setup and Inspection

CREATE EXTENSION postgis;                       -- once per database
SELECT postgis_full_version();                  -- check that it works
SELECT * FROM geometry_columns;                 -- spatial tables, geometry types and SRIDs
SELECT Find_SRID('public', 'roads', 'geom');    -- the SRID of a column
SELECT DISTINCT ST_GeometryType(geom), ST_SRID(geom) FROM roads;   -- what is really inside

Creating Spatial Tables and Indexes

CREATE TABLE places (
  id    serial PRIMARY KEY,
  name  text NOT NULL,
  geom  geometry(Point, 4326)            -- type and SRID are enforced
);

-- Add a geometry column to an existing table
ALTER TABLE stations ADD COLUMN geom geometry(Point, 4326);

-- The spatial index: the single most important performance step
CREATE INDEX places_geom_idx ON places USING GIST (geom);
VACUUM ANALYZE places;                   -- update statistics after loading data

-- Change the SRID label (does NOT move the data)
SELECT UpdateGeometrySRID('places', 'geom', 4326);

-- Reproject a whole column (DOES convert the coordinates)
ALTER TABLE roads
  ALTER COLUMN geom TYPE geometry(LineString, 32631)
  USING ST_Transform(geom, 32631);

Note the difference between labeling (ST_SetSRID, UpdateGeometrySRID) and converting (ST_Transform). It is the same trap as set_crs and to_crs in GeoPandas, and the principle comes from Coordinate Reference Systems (CRS) Explained Simply.


Constructors: Making Geometries

FunctionWhat it doesExample
ST_MakePoint(x, y)A point. Longitude first, then latitude.ST_MakePoint(2.35, 48.85)
ST_SetSRID(geom, srid)Labels a geometry with an SRIDST_SetSRID(ST_MakePoint(2.35, 48.85), 4326)
ST_GeomFromText(wkt, srid)A geometry from text (WKT)ST_GeomFromText('POINT(2.35 48.85)', 4326)
ST_GeomFromGeoJSON(json)A geometry from GeoJSON textST_GeomFromGeoJSON('{"type":"Point","coordinates":[2.35,48.85]}')
ST_MakeLine(a, b) or ST_MakeLine(array)A line from pointsST_MakeLine(p1, p2)
ST_MakeEnvelope(xmin, ymin, xmax, ymax, srid)A rectangleST_MakeEnvelope(2.2, 48.8, 2.5, 48.9, 4326)
ST_Collect(geom)Aggregate: gathers geometries into one collectionST_Collect(geom) with GROUP BY
ST_Multi(geom)Converts a single geometry to its multi versionST_Multi(geom)
ST_GeneratePoints(polygon, n)Random points inside a polygonST_GeneratePoints(geom, 100)

Build points from a table of coordinates:

UPDATE stations
SET geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326);

Accessors and Outputs: Looking Inside

FunctionReturns
ST_AsText(geom)WKT text
ST_AsGeoJSON(geom)GeoJSON geometry
ST_AsEWKT(geom)WKT including the SRID
ST_X(point), ST_Y(point)The coordinates of a point
ST_SRID(geom)The SRID
ST_GeometryType(geom)Type, such as ST_Polygon
ST_NumPoints(geom)Number of vertices
ST_NumGeometries(geom)Number of parts in a multi-geometry
ST_Envelope(geom)The bounding rectangle
ST_Dump(geom)Splits a multi-geometry into parts (set-returning)
ST_Boundary(geom)The boundary of a geometry
ST_ExteriorRing(polygon)The outer ring

Break multipart features into single parts:

SELECT id, (ST_Dump(geom)).geom AS geom
FROM parcels;

Measurements

FunctionReturnsRemember
ST_Area(geom)AreaIn CRS units squared. Use a projected CRS, or cast to geography
ST_Length(geom)Length of linesSame caution
ST_Perimeter(geom)Perimeter of polygonsSame caution
ST_Distance(a, b)Shortest distanceCRS units. Not index-friendly in filters
ST_Azimuth(a, b)Direction from a to b, in radians
ST_ClosestPoint(a, b)The point on a closest to b
ST_ShortestLine(a, b)The line joining the closest points
ST_Extent(geom)Aggregate: the bounding box of many rows

On the curved Earth, with latitude and longitude, cast to geography to get meters:

SELECT name, ST_Area(geom::geography) / 1000000 AS km2 FROM districts;
SELECT SUM(ST_Length(geom::geography)) / 1000 AS km FROM roads;
SELECT ST_Distance(a.geom::geography, b.geom::geography) AS meters FROM places a, places b WHERE a.id = 1 AND b.id = 2;

Spatial Relationships (Predicates)

These return true or false, and are the heart of spatial joins and filters. They correspond to the concepts in How Does GIS Work? Layers, Data, and Analysis Explained.

FunctionTrue when
ST_Intersects(a, b)They share any space. The most used predicate, and uses the index
ST_Disjoint(a, b)They share nothing (the opposite)
ST_Contains(a, b)b is completely inside a
ST_Within(a, b)a is completely inside b
ST_Covers(a, b)Like Contains, but boundary points count as inside
ST_Touches(a, b)They share a boundary only, not interiors
ST_Crosses(a, b)A line passes through another geometry
ST_Overlaps(a, b)They partially overlap, with the same dimension
ST_Equals(a, b)The same shape
ST_DWithin(a, b, distance)Within a distance. The right way to ask “nearby”, using the index
a && bTheir bounding boxes overlap. A very fast pre-filter

Never write ST_Distance(a, b) < 500 in a filter. Use ST_DWithin(a, b, 500), which can use the spatial index.


Processing and Overlay

FunctionDoes
ST_Buffer(geom, distance)A zone around the geometry. Distance in CRS units
ST_Intersection(a, b)The shared part
ST_Union(a, b) or ST_Union(geom)Merges geometries. The aggregate form dissolves
ST_Difference(a, b)a minus b
ST_SymDifference(a, b)What is in one but not both
ST_Centroid(geom)The geometric center. May fall outside irregular shapes
ST_PointOnSurface(geom)A point guaranteed to be inside
ST_ConvexHull(geom)The smallest convex polygon that contains it
ST_Simplify(geom, tolerance)Fewer vertices. For display, not analysis
ST_SimplifyPreserveTopology(geom, tolerance)Simplifies without creating invalid shapes
ST_SnapToGrid(geom, size)Rounds coordinates to a grid
ST_Segmentize(geom, max_length)Adds vertices to long segments
ST_LineMerge(geom)Joins connected lines
ST_Split(geom, blade)Cuts a geometry with another
ST_Transform(geom, srid)Reprojects
ST_Force2D(geom)Drops Z and M values

The overlay functions are the SQL versions of the tools in Buffer, Clip, Intersect, Union: Overlay Tools Explained.


Validity and Repair

-- Which geometries are invalid, and why?
SELECT id, ST_IsValidReason(geom) FROM parcels WHERE NOT ST_IsValid(geom);

-- Repair them
UPDATE parcels SET geom = ST_MakeValid(geom) WHERE NOT ST_IsValid(geom);

-- Keep the geometry type consistent after repair (MakeValid can return collections)
UPDATE parcels
SET geom = ST_Multi(ST_CollectionExtract(ST_MakeValid(geom), 3))
WHERE NOT ST_IsValid(geom);

ST_CollectionExtract(geom, 3) keeps only the polygon parts (1 is points, 2 is lines, 3 is polygons). Repair is routine after any import. See Top 10 Most Common GIS Errors and How to Fix Them.


Patterns You Will Use All the Time

1. Count points in polygons

SELECT d.id, d.name, COUNT(s.id) AS n_schools
FROM districts d
LEFT JOIN schools s ON ST_Within(s.geom, d.geom)
GROUP BY d.id, d.name
ORDER BY n_schools DESC;

The LEFT JOIN keeps districts with zero schools. An inner join would drop them.

2. Assign each point the attributes of the polygon it falls in

SELECT s.id, s.name, d.name AS district
FROM schools s
JOIN districts d ON ST_Within(s.geom, d.geom);

3. Everything within a distance

-- Hospitals within 2 km of a school (projected CRS in meters)
SELECT s.name AS school, h.name AS hospital
FROM schools s
JOIN hospitals h ON ST_DWithin(s.geom, h.geom, 2000);

4. The nearest feature, for every feature

SELECT s.id, n.hospital_id, n.dist
FROM schools s
CROSS JOIN LATERAL (
  SELECT h.id AS hospital_id, h.geom <-> s.geom AS dist
  FROM hospitals h
  ORDER BY h.geom <-> s.geom
  LIMIT 1
) n;

The <-> operator orders by distance using the index, and LATERAL runs the small subquery once per school. The distance is in CRS units (degrees for EPSG:4326), so use a projected CRS for meters, or treat the result as a ranking only.

5. The k nearest neighbors of a point

SELECT name
FROM places
ORDER BY geom <-> ST_SetSRID(ST_MakePoint(2.3522, 48.8566), 4326)
LIMIT 5;

6. Area of overlap (an intersection with measurement)

SELECT p.parcel_id, f.flood_class,
       ST_Area(ST_Intersection(p.geom, f.geom)) AS overlap_m2,
       ST_Area(ST_Intersection(p.geom, f.geom)) / ST_Area(p.geom) AS share_of_parcel
FROM parcels p
JOIN flood_zones f ON ST_Intersects(p.geom, f.geom);

The ST_Intersects in the join condition lets the database use the index, and the intersection is computed only for pairs that really overlap.

7. Dissolve by an attribute

SELECT region, ST_Union(geom) AS geom, SUM(population) AS population
FROM districts
GROUP BY region;

ST_Union merges the shapes and removes internal boundaries. ST_Collect just bundles them, without merging, and is much faster when you don’t need a true dissolve.

8. Clip to a bounding box quickly

SELECT id, name, geom
FROM roads
WHERE geom && ST_MakeEnvelope(2.2, 48.8, 2.5, 48.9, 4326);

9. Buffer in meters on latitude and longitude data

SELECT id, ST_Buffer(geom::geography, 500)::geometry AS geom
FROM schools;

10. Cluster points

SELECT id,
       ST_ClusterDBSCAN(geom, eps := 200, minpoints := 10) OVER () AS cluster_id
FROM incidents;                           -- geom in a projected CRS, eps in meters

ST_ClusterKMeans(geom, 5) OVER () groups the points into five clusters. See Spatial Clustering: DBSCAN, K-Means, and Cluster Analysis for choosing parameters.

11. A hexagon grid and counts per cell

WITH bounds AS (
  SELECT ST_SetSRID(ST_Extent(geom)::geometry, 32631) AS geom FROM incidents
)
SELECT g.i, g.j, g.geom, COUNT(p.id) AS n
FROM bounds
CROSS JOIN LATERAL ST_HexagonGrid(1000, bounds.geom) AS g
LEFT JOIN incidents p ON ST_Intersects(g.geom, p.geom)
GROUP BY g.i, g.j, g.geom;

Equal-sized cells are a fair alternative to irregular zones, as discussed in Choropleth, Heat, and Proportional Symbol Maps: When to Use Each.

12. Position along a line (linear referencing)

-- Meters from the start of the road at which each crash occurred (projected CRS in meters)
SELECT c.crash_id,
       ST_LineLocatePoint(r.geom, c.geom) * ST_Length(r.geom) AS meters_from_start
FROM roads r
JOIN crashes c ON ST_DWithin(r.geom, c.geom, 20)
WHERE r.road_id = 'A7';

-- The point 3,500 m along the road
SELECT ST_LineInterpolatePoint(geom, 3500.0 / ST_Length(geom)) FROM roads WHERE road_id = 'A7';

13. Reprojecting on the fly, for a filter in meters

SELECT id
FROM schools
WHERE ST_DWithin(ST_Transform(geom, 32631), ST_Transform(:point_geom, 32631), 500);

If you run this often on a large table, store a column already in the projected CRS, with its own index, instead of transforming each row every time.

14. Rank within groups with a window function

SELECT *
FROM (
  SELECT d.name AS district, s.name AS school, s.pupils,
         ROW_NUMBER() OVER (PARTITION BY d.id ORDER BY s.pupils DESC) AS rk
  FROM schools s
  JOIN districts d ON ST_Within(s.geom, d.geom)
) ranked
WHERE rk <= 3;       -- the three largest schools in each district

15. Update one table from another, spatially

UPDATE schools s
SET district_id = d.id
FROM districts d
WHERE ST_Within(s.geom, d.geom);

Getting Data Out

SELECT ST_AsGeoJSON(geom) FROM districts LIMIT 1;           -- one geometry

-- A complete GeoJSON FeatureCollection
SELECT jsonb_build_object(
         'type', 'FeatureCollection',
         'features', jsonb_agg(ST_AsGeoJSON(t.*)::jsonb)
       )
FROM (SELECT id, name, geom FROM districts) t;

-- A vector tile (the basis of modern web maps), for tile z=12, x=2074, y=1409
SELECT ST_AsMVT(q, 'districts', 4096, 'geom')
FROM (
  SELECT id, name,
         ST_AsMVTGeom(ST_Transform(geom, 3857), ST_TileEnvelope(12, 2074, 1409), 4096, 64, true) AS geom
  FROM districts
  WHERE ST_Transform(geom, 3857) && ST_TileEnvelope(12, 2074, 1409)
) q;

The vector tile example shows how a database can serve web maps directly. See How to Create a Web Map (Leaflet, Mapbox, OpenLayers). To export from the command line, use ogr2ogr, as in Best Free and Open-Source GIS Tools.


Performance Tips

  • Always index geometry columns with GIST, and run VACUUM ANALYZE after bulk loads.
  • Use index-friendly functions: ST_DWithin rather than ST_Distance < x, and ST_Intersects, ST_Within or && in join conditions.
  • Don’t wrap an indexed column in a function in a filter, such as ST_Transform(geom, 3857) && box, on a huge table. Store a transformed copy with its own index instead.
  • Keep one SRID per column, in a projected CRS suited to your work. See Map Projections: How to Choose the Right One.
  • Read the query plan: EXPLAIN ANALYZE SELECT ... shows whether the index is used. Look for “Index Scan” rather than “Seq Scan” on big tables.
  • Filter by attributes first, to reduce the rows before heavy geometry work.
  • Subdivide huge, complex polygons with ST_Subdivide so that indexes work better against them.
  • Simplify for display, not for analysis.
  • Select only the columns you need. Heavy geometries slow down results.
  • Use materialized views for expensive, rarely changing results, and refresh them on a schedule.
  • Join on indexed keys whenever an attribute relationship is available.

Common Errors and What They Mean

Message or symptomLikely causeFix
Operation on mixed SRID geometriesThe two geometries have different SRIDsReproject one with ST_Transform, or fix a wrong label
Geometry type (Point) does not match column type (MultiPoint)Single versus multi geometryWrap with ST_Multi(geom)
Geometry has Z dimension but column does not3D data into a 2D columnST_Force2D(geom)
TopologyException or side location conflictAn invalid geometry in an overlayST_MakeValid(geom) first
function st_… does not existThe extension is missing, or argument types are wrongCREATE EXTENSION postgis; or cast arguments
Points in the wrong place, or the seaLongitude and latitude swapped, or wrong SRIDST_MakePoint(lon, lat), and check the SRID
Distances or areas look absurdMeasuring in degreesUse a projected SRID, or ::geography
A join returns nothingSRID mismatch, wrong predicate, or empty geometriesCheck SRIDs and test with ST_Intersects
A query is very slowMissing index, or a function defeating the indexAdd a GIST index, and use ST_DWithin
More rows than expected after a joinA one-to-many spatial relationshipAggregate, or choose a stricter predicate

Beyond PostGIS: Other Dialects

The ideas are universal, but names and details vary.

  • SpatiaLite and GeoPackage (SQLite): many ST_ functions work similarly, such as ST_Intersects, ST_Buffer and ST_Area, with some differences in names, for example MakePoint(x, y, srid), and spatial indexes created with a special function. GDAL’s command-line tools can run SQL against a GeoPackage: ogrinfo -dialect SQLite -sql "SELECT ..." data.gpkg. See Shapefile vs. GeoJSON vs. GeoPackage: Which Format to Use?
  • QGIS virtual layers: Layer > Add Layer > Add/Edit Virtual Layer lets you write SQL across your loaded layers, using the SpatiaLite dialect. A great way to practice.
  • DuckDB with the spatial extension: reads files such as GeoPackage and Parquet directly, with ST_ functions, and is very fast for analysis.
  • BigQuery (GEOGRAPHY): uses ST_GEOGPOINT(lon, lat), ST_DISTANCE, ST_DWITHIN and similar, in meters, on the curved Earth.
  • SQL Server and others: spatial types and methods use different syntax, and some take latitude first, for example geography::Point(lat, lon, 4326). Check the order carefully.
  • Oracle Spatial, MySQL and others: support spatial SQL with their own functions and index types.

When you move between systems, read the documentation for coordinate order, units and index syntax. Those are the three places where the same idea gets different spellings.


A One-Screen Summary

  • Declare: geometry(Type, SRID), index with USING GIST.
  • Build: ST_SetSRID(ST_MakePoint(lon, lat), 4326).
  • Convert: ST_Transform(geom, srid). Label: ST_SetSRID. Never mix them up.
  • Measure in meters: a projected SRID, or ::geography.
  • Ask “within”: ST_Within, ST_Intersects, ST_Contains.
  • Ask “nearby”: ST_DWithin. Nearest: ORDER BY geom <-> point LIMIT k.
  • Overlay: ST_Intersection, ST_Union, ST_Difference, ST_Buffer.
  • Repair: ST_IsValid, ST_MakeValid.
  • Summarize: GROUP BY with COUNT, SUM, ST_Union, ST_Collect.
  • Explore: EXPLAIN ANALYZE, geometry_columns, ST_GeometryType, ST_SRID.

Final Thoughts

Spatial SQL is one of those skills that pay back for decades, because the language barely changes while the tools around it come and go. Once you can think in rows, joins and predicates, questions that need minutes in a desktop GIS take milliseconds in a database, and they can run unattended, on millions of features, every night.

Print this page, or better, write your own sheet in your own words as you learn. The act of writing it down is what puts the patterns into your head. And when you feel confident, move the heavy parts of your Python workflows into the database, as described in GeoPandas and Shapely: Vector Data in Python and Geospatial Development & Automation: The Ultimate Guide.

Where to go next: put your queries to work behind web services with Intro to Web GIS APIs and OGC Standards (WMS, WFS, WMTS), and automate them with Automating Workflows with ModelBuilder and QGIS Processing.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.