15. Spatial Data: PostGIS Masterclass
The World in Your Database
PostgreSQL is the undisputed king of spatial data thanks to PostGIS. It turns your database into a Geographic Information System (GIS), allowing you to store coordinates, shapes, and perform complex geometry math like 'Find all delivery drivers within 5km of this customer'.
Geometry vs Geography
PostGIS provides two main data types for spatial work:
- Geometry: Uses a flat, Cartesian plane (X, Y). Best for maps of building interiors or small local areas.
- Geography: Uses a spherical model (Earth). It accounts for the curvature of the Earth, making distance calculations accurate over long distances.
-- Enabling the extension CREATE EXTENSION postgis; -- Creating a table with spatial data CREATE TABLE locations ( id SERIAL PRIMARY KEY, name TEXT, geom GEOGRAPHY(Point, 4326) -- 4326 is the standard GPS coordinate system (WGS84) );
The Spatial Join
One of the most powerful features of PostGIS is joining tables based on their physical location. This is how apps like Uber or Yelp work.
-- Find stores within 1000 meters of a specific point SELECT name, ST_Distance(geom, ST_MakePoint(-122.4, 37.7)::geography) as distance FROM stores WHERE ST_DWithin(geom, ST_MakePoint(-122.4, 37.7)::geography, 1000) ORDER BY distance;
Performance: GiST Indexes
Standard B-Tree indexes don't work for shapes. PostGIS uses GiST (Generalized Search Tree) indexes. It creates a hierarchy of Bounding Boxes so the database can quickly discard large areas of the map that don't match your query.
Knowledge Check
Ready to test your understanding of 15. Spatial Data: PostGIS Masterclass?