Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries)
Query locations and distances with PostGIS geometry and geography types.
In plain words
Store places as points on a map, then ask the database which points are near you or inside an area.
Think of it like…
A paper map with a grid: the grid (the index) lets you look only at the squares near a point instead of checking every shop in the country, and a piece of string cut to 3 km tells you which of those shops are close enough.
Where you’ve seen it
A food-delivery app lists open restaurants within 3 km of the customer, nearest first: SELECT id, name, ST_Distance(location, ST_MakePoint(73.8567, 18.5204)::geography) AS metres FROM restaurants WHERE is_open AND ST_DWithin(location, ST_MakePoint(73.8567, 18.5204)::geography, 3000) ORDER BY location <-> ST_MakePoint(73.8567, 18.5204)::geography LIMIT 20; A GiST index on location keeps it at a few milliseconds across 200,000 restaurants.
Words you’ll hear
- geography
- Points and shapes on the earth's surface; distances in metres.
- geometry + SRID
- Shapes on a plane in a coordinate system; SRID 4326 is longitude/latitude (WGS 84).
- ST_DWithin
- True if two shapes are within a distance; index-assisted.
- <-> (KNN)
- Distance operator for ORDER BY … LIMIT nearest-neighbour searches.
Visual diagram
Theory & example queries
Types, coordinates and indexes
Enable PostGIS with CREATE EXTENSION postgis; and add a column such as location geography(Point, 4326). Points are built with ST_MakePoint(longitude, latitude); the longitude-first order trips up almost everyone, and swapped coordinates put Pune in the Indian Ocean. geography computes distances on the spheroid in metres, which is what most apps want. geometry is faster for heavy analysis, but distances are in the SRID's units (degrees for 4326), so project to a metric SRID for planar measurements.
Create a spatial index with CREATE INDEX ON restaurants USING gist (location). Index-aware functions (ST_DWithin, ST_Intersects, ST_Contains, the <-> operator in ORDER BY) use a bounding-box search on the index first, then check exact shapes only for candidates.
CREATE EXTENSION IF NOT EXISTS postgis;CREATE TABLE restaurants ( id bigint PRIMARY KEY, name text, is_open boolean, location geography (Point, 4326) NOT NULL);CREATE INDEX restaurants_location_gist ON restaurants USING gist (location);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command status
Note: PostgreSQL command tags are representative. Names already existing or insufficient privileges can produce notices or errors instead.
Key takeaway: geography in metres, longitude first, GiST index on the column.
Radius, nearest and point-in-polygon
For "within 3 km", use ST_DWithin(location, point, 3000), never ST_Distance(location, point) < 3000: the latter computes the distance to every row and can't use the index. For "nearest N", use ORDER BY location <-> point LIMIT N, which walks the index in distance order; combine it with ST_DWithin when you also need a maximum radius.
Delivery zones and city boundaries are polygons: SELECT z.name FROM zones z WHERE ST_Contains(z.boundary, ST_SetSRID(ST_MakePoint(73.8567, 18.5204), 4326)); finds the zone serving a customer (with geometry columns and a GiST index on boundary). MySQL also supports spatial types and SRID-aware functions such as ST_Distance_Sphere, but PostGIS has far more functions and tooling.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT z.name, COUNT(o.id) AS ordersFROM zones z LEFT JOIN orders o ON ST_Contains (z.boundary, o.drop_point) AND o.created_at >= '2026-11-01'GROUP BY z.nameORDER BY orders DESC;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative zone totals3 sample rows
| name | orders |
|---|---|
| Central | 184 |
| East | 121 |
| Airport | 0 |
Note: Assumes sample zone polygons and order drop points for November 2026; COUNT(o.id) keeps the zone with no matching orders.
Key takeaway: ST_DWithin for radius, <-> for nearest, ST_Contains for zones.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Store points correctly
Use geography(Point, 4326) for lon/lat data and build points with longitude first.
ST_MakePoint(73.8567, 18.5204)::geography
When to use it & trade-offs
What it is
PostGIS adds spatial types and functions to PostgreSQL. A geography column stores longitude/latitude points on the earth and measures distances in metres; a geometry column works on a flat plane in the units of its coordinate system (SRID). The everyday queries are "within X metres" (ST_DWithin), "nearest N" (ORDER BY location <-> point LIMIT N) and "which zone contains this point" (ST_Contains), all made fast by a GiST index.
Why it matters: Delivery radius checks, store finders, ride matching, geofencing and regional reporting are all spatial queries. Doing them with latitude and longitude columns and hand-written formulas is slow and error-prone. PostGIS is the standard tool, and spatial questions appear in interviews for logistics, mobility and marketplace companies.
When to reach for it
- Store and restaurant finders
- Delivery-radius and geofence checks
- Counting events per region or zone
When to avoid or be careful
- WHERE ST_Distance(…) < x instead of ST_DWithin
- Swapping latitude and longitude
- Measuring distances in degrees with SRID 4326 geometry
Ways to answer "what's near me?"
Strengths: Correct on the globe; index-assisted radius and KNN queries.
Watch out: Slightly slower than geometry for heavy analysis.
Strengths: Fast planar maths; huge function library.
Watch out: Must choose and transform to a suitable projection.
Strengths: No extension needed.
Watch out: No spatial index; formula errors; slow at scale.
Interview signals & numbers to know
When this topic comes up
- “Find drivers within 2 km”
- “Nearest 10 stores to a user”
- “Which delivery zone is this address in?”
- PostGIS
- Location-based features
Benchmarks & rules of thumb
- 4326
- SRID for longitude/latitude (WGS 84)
- metres
- geography distance units
- lon, lat
- ST_MakePoint argument order
Common mistakes & follow-ups
Common interview mistakes
- Calling ST_MakePoint(lat, lon) and getting restaurants that are thousands of kilometres away.
- Filtering with ST_Distance(location, point) < 3000, which computes the distance to every row.
- Using geometry with SRID 4326 and passing 3000 as a distance, which means 3,000 degrees.
Likely interviewer follow-ups
- How would you find the 10 nearest stores to a user efficiently?
- What's the difference between geometry and geography in PostGIS?
- Why is ST_DWithin preferred to ST_Distance in a WHERE clause?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries) with hands-on SQL practice and interview Q&A.